开发者

Find text between string

How to extr开发者_Python百科act text using perl from string like this:


Get text 1 ...
---------------------------------------------------------------------------------------------
Get text 2 ...
---------------------------------------------------------------------------------------------
Get text 3
---------------------------------------------------------------------------------------------

The result should be like this:

%texts =  ( 'text1' => 'Get text 1 ...', 'text2' => 'Get text 2 ...',
'text3' => 'Get text 3 ...' )

Something like PHP preg_match_all.

Many thanks


If your preg_macth_all looks like preg_match_all('/(foo)/', $text, $matches), the perl equivalent is something like @matches = $text=~/(foo)/g.


I'm not sure if this is what you want, but the following code extracts the lines from the string you gave and puts them in a hash:

use Data::Dumper;

my $str = 'Get text 1 ...
---------------------------------------------------------------------------------------------
Get text 2 ...
---------------------------------------------------------------------------------------------
Get text 3
---------------------------------------------------------------------------------------------';


my %hash = (
    'text1' => $str =~ /.*text 1.*/g,
    'text2' => $str =~ /.*text 2.*/g,
    'text3' => $str =~ /.*text 3.*/g);


print Dumper(\%hash);

The output of this snippet is:

$VAR1 = {
          'text2' => 'Get text 2 ...',
          'text1' => 'Get text 1 ...',
          'text3' => 'Get text 3'
        };


my $i = 1;
my %text = ();
open my $fh, "<", \$the_string;
while (<$fh>) {
    if (/--------------/) {  # text separator
        $i++;
    } else {
        $text{"text$i"} .= $_;
    }
}


In Perl >= 5.10, this should be:

while( $string =~ /^\w+\s+(\w+)\s+(\w+)[^\n\r]*/pgms ) {
   $texts{$1.$2} = ${^MATCH}
}

Regards

rbo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜