成功匹配后继续正则表达式匹配

时间:2011-11-28 22:22:11

标签: regex perl

对于下面的代码,我需要更改什么(在我的正则表达式中?),以便打印出$string中该匹配中出现的正则表达式的所有实例?

所以现在输出只是匹配正则表达式的第一个实例,但我想打印出以下2个实例。我认为正则表达式末尾的/ 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 个答案:

答案 0 :(得分:4)

你是在循环中完成的:

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

答案 1 :(得分:3)

只需更改打印结果的方式:)

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

答案 2 :(得分:1)

尝试

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

将它们全部捕获到数组@matches

答案 3 :(得分: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等等。