2011-11-28 76 views
0

對於下面的代碼,我需要更改哪些內容(在我的正則表達式中?),以便打印出在$string中匹配中出現的正則表達式的所有實例?成功匹配後繼續進行正則表達式匹配

所以現在輸出只是第一個匹配正則表達式的實例,但我還想打印出以下兩個實例。我認爲在正則表達式結尾的/ g會做到這一點。

#!/usr/bin/perl 

$start = '<!--Start here-->'; 
$end = '<!--End now-->'; 
$string = "Lorem ipsum dolor sit amet, consectetur <!--Start here-->adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per <!--End now-->conubia nostra, per inceptos himenaeos. <!--Start here-->Mauris ac elementum enim. <!--End now-->Etiam hendrerit accumsan sodales. Morbi mi tortor, adipiscing in interdum eu, volutpat quis neque. Aenean tincidunt ornare risus, id faucibus augue dictum ut. Nullam aliquet metus vel nibh ullamcorper ornare. Vestibulum a sapien augue. Praesent tellus nulla, congue non vestibulum eget, venenatis eu tellus. <!--Start here-->Donec varius porttitor blandit.<!--End now--> a sapien augue ipsum dolor."; 
$string =~ m/(($start)(.+?)($end))/g; 
print $1; 

回答

4

你做一個循環:

print $1 while ($string =~ m/(($start)(.+?)($end))/g); 
1

嘗試

my @matches = $string =~ m/(($start)(.+?)($end))/g; 

將它們全部捕捉到陣列@matches

3

只要改變你的打印結果的方式:)

while ($subject =~ m/(($start)(.+?)($end))/g) { 
    print $1, "\n"; 
} 
0

這可能不是捕獲它的最好方式,除非你真的想要開始,結束,完整的短語包括開始和結束,內容等。正則表達式運算符在列表上下文中返回匹配結果,而你可以使用該做的事:

#!/usr/bin/perl 
use strict; 
use warnings; 
use 5.010; 

my $start = '<!--Start here-->'; 
my $end = '<!--End now-->'; 
my $string = "Lorem ipsum dolor sit amet, consectetur <!--Start here-->adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per <!--End now-->conubia nostra, per inceptos himenaeos. <!--Start here-->Mauris ac elementum enim. <!--End now-->Etiam hendrerit accumsan sodales. Morbi mi tortor, adipiscing in interdum eu, volutpat quis neque. Aenean tincidunt ornare risus, id faucibus augue dictum ut. Nullam aliquet metus vel nibh ullamcorper ornare. Vestibulum a sapien augue. Praesent tellus nulla, congue non vestibulum eget, venenatis eu tellus. <!--Start here-->Donec varius porttitor blandit.<!--End now--> a sapien augue ipsum dolor."; 

my @matches = ($string =~ m/$start(.+?)$end/g); 
say for @matches; 

輸出:

adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per 
Mauris ac elementum enim. 
Donec varius porttitor blandit. 

即沒有與$1 $2 $3

亂搞