perlre匹配捕获组在同一行上多次

时间:2016-06-30 20:03:23

标签: regex perl

鉴于以下内容;

<tag id='1'><![CDATA[this is a string of text]]><tag id='2'><![CDATA[this is another string of text]]><tag id='3'><![CDATA[this is the last string of text]]>

我尝试匹配CDATA方括号内的文本字符串,以返回每个匹配而不必先拆分该行。我可以通过分割线来实现这一点(见下文),但我正在尝试更好地理解perl正则表达式匹配以及我是否可以使用正则表达式完成相同的操作。

my $string = qq(<tag id='1'><![CDATA[this is a string of text]]><tag id='2'><![CDATA[this is another string of text]]><tag id='3'><![CDATA[this is the last string of text]]>)
my @splitline = split(/\</, $string);
foreach(@splitline){
   if ($_ =~ /\!\[CDATA\[(.*?)\]\]/){
      print "$1\n";
   }
}

以上结果是

  

这是一串文字

     

这是另一个文本字符串

     

这是最后一个文本字符串

如果我试试这个,它只返回第一场比赛。

my $string = qq(<tag id='1'><![CDATA[this is a string of text]]><tag id='2'><![CDATA[this is another string of text]]><tag id='3'><![CDATA[this is the last string of text]]>)
if ($string =~ /\!\[CDATA\[(.*?)\]\]/){
   print "$1\n";
}

将我的正则表达式更改为以下内容将返回无数据

$string =~ /\!\[CDATA\[(.*?)+\]\]/g

2 个答案:

答案 0 :(得分:2)

使用&#34;重复匹配&#34; Perl中的功能,while( ... /g ...:

更改

if ($string =~ /\!\[CDATA\[(.*?)\]\]/){

while ($string =~ /\!\[CDATA\[(.*?)\]\]/g){

答案 1 :(得分:1)

问题是你在标量上下文中调用匹配(带有if语句的I.E)。相反,您应该在列表上下文中调用它并将所有匹配加载到数组中。然后你可以检查数组并打印结果。

my $string = qq(<tag id='1'><![CDATA[this is a string of text]]><tag id='2'><![CDATA[this is another string of text]]><tag id='3'><![CDATA[this is the last string of text]]>);

my @matches = $string =~ /\!\[CDATA\[(.*?)\]\]/g;

print join("\n",@matches) if @matches;

输出

this is a string of text
this is another string of text
this is the last string of text

如果你真的想在标量上下文中调用它,那么你将需要迭代ver所有的匹配,因为perl文档声明在标量事件中它将跟踪每个匹配的位置。

my $string = qq(<tag id='1'><![CDATA[this is a string of text]]><tag id='2'><![CDATA[this is another string of text]]><tag id='3'><![CDATA[this is the last string of text]]>);

while ($string =~ /\!\[CDATA\[(.*?)\]\]/g){
    print "$1\n";
}
相关问题