【问题标题】:Current position for regex matching in perlperl 中正则表达式匹配的当前位置
【发布时间】:2012-10-12 03:51:38
【问题描述】:

我想随后在两条路径之间提取文本 sn-p 在一个长字符串中。

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

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

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

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

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

编辑:

"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" @@@"

但它只会给我第一个。

【问题讨论】:

  • 嗨,你是对的,它很低。但是,如果答案不够好怎么办?

标签: regex perl matching


【解决方案1】:

你想要的是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

【讨论】:

  • 太棒了!如果您不知道这些表达式作为前瞻匹配,真的很难找到;)非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-10
  • 2017-01-03
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多