Perl正则表达式 - 为什么正则表达式/ [0-9 \。] +(\,)/匹配逗号

时间:2012-11-21 21:24:33

标签: regex perl

以下似乎与,匹配 有人可以解释原因吗?

我想匹配多个数字或点,以逗号结尾。

 123.456.768,
 123,
 .,
 1.2,

但是,执行以下操作会意外地打印,

my $text = "241.000,00";
foreach my $match ($text =~ /[0-9\.]+(\,)/g){
    print "$match \n";
}
print $text; 

# prints 241.000,
#        ,

更新:
逗号匹配是因为: In list context, //g returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex 按照定义here.

5 个答案:

答案 0 :(得分:4)

foreach循环中的匹配位于列表上下文中。在列表上下文中,匹配返回其捕获的内容。 Parens表示捕获,而不是整个正则表达式。你有一个逗号周围的parens。你想要它反过来,把它们放在你想要的地方。

my $text = "241.000,00";

# my($foo) puts the right hand side in list context.
my($integer_part) = $text =~ /([0-9\.]+),/;

print "$integer_part\n";  # 241.000

答案 1 :(得分:4)

使用zero-width positive look-ahead assertion从匹配项中排除逗号:

$text =~ /[0-9\.]+(?=,)/g

答案 2 :(得分:3)

如果您不想匹配逗号,请使用前瞻断言:

/[0-9\.]+(?=,)/g

答案 3 :(得分:2)

你抓错了!将逗号从逗号周围移到数字周围。

$text =~ /([0-9\.]+),/g

答案 4 :(得分:1)

您可以使用前瞻替换逗号,或者只是完全排除逗号,因为它不是您要捕获的内容的一部分,在这种情况下它不会有所区别。但是,模式将逗号而不是数字放入捕获组1,然后甚至不通过捕获组引用,而是返回整个匹配。

这是检索捕获组的方式:

$mystring = "The start text always precedes the end of the end text.";
if($mystring =~ m/start(.*)end/) {
    print $1;
}