perl中正则表达式匹配的当前位置

时间:2012-10-22 10:41:26

标签: regex perl matching

我想随后提取两个路径之间的文本片段 在一个长串。

因此,我使用这样的东西:

while($data=~ m/\"(.:\\.*?)\".:\\/sg){...}

`\".:\\(.*?)之前是"的路径。 并且,由于两个路径之间的部分可以是任何字符, 我用下一个路径的开头完成正则表达式:\".:\\

不幸的是,这样代码会跳过一次匹配。我相信, 这是因为后续搜索将在最后一次\".:\\之后开始,因此它只会找到下一个。

如何确保设置了搜索的poisition指针 回到正则表达式的最后一部分之前(之前:\".:\\

编辑:

"y:\car\main.cs@@jung" "Added format of version number to all sub-parts.

"Hallo Peter"

@@@ "tool kit" @@@"

"y:\car\main.cs@@kkla" (lkaskdn awdiwj)

"The filter "function of the new version works with Excel 2007"only,
but is the correct filter structure.

@@@ "Huihu boy" @@@"

这个文件应该给我两个$ 1的结果:

1

y:\car\main.cs@@jung" "Added format of version number to all sub-parts.

"Hallo Peter"

@@@ "tool kit" @@@"

2

y:\car\main.cs@@kkla" (lkaskdn awdiwj)

"The filter "function of the new version works with Excel 2007"only,
but is the correct filter structure.

@@@ "Huihu boy" @@@"

但它只会给我第一个。

1 个答案:

答案 0 :(得分:2)

你想要的是look-ahead assertion。这符合您的模式之后的内容,而不包括匹配中的“某事”。语法是:

(?=...)

我没有正则表达式的示例数据,所以这里只是一个简单的示例:

use strict;
use warnings;

my $string = "foobarbarbarnbar";

print "Regular matches: ";
#regular matching
while ($string =~ /(\w+?)bar/g)
{
   print " $1"; 
}
#lookahead
print "\nLookahead matches: ";
while ($string =~ /(\w+?)(?=bar)/g)
{
   print " $1"; 
}

输出:

Regular matches:  foo bar n 
Lookahead matches:  foo bar bar barn