本文介绍了Perl 中的模式匹配是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道模式匹配在 Perl 中是如何工作的.
I want to know how pattern matching works in Perl.
我的代码是:
my $var = "VP KDC T. 20, pgcet. 5, Ch. 415, Refs %50 Annos";
if($var =~ m/(.*)\,(.*)/sgi)
{
print "$1\n$2";
}
我了解到应该匹配第一次出现的逗号.但这里最后一次匹配.我得到的输出是:
I learnt that the first occurrence of comma should be matched. but here the last occurrence is being matched. The output I got is:
VP KDC T. 20, pgcet. 5, Ch. 415
Refs %50 Annos
有人可以解释一下这种匹配是如何工作的吗?
Can someone please explain me how this matching works?
推荐答案
来自 docs一个>:
默认情况下,量化的子模式是贪婪的",也就是说,它会尽可能多地匹配(给定一个特定的起始位置),同时仍然允许模式的其余部分匹配
所以,首先 (.*)
会尽可能多.
So, first (.*)
will take as much as possible.
简单的解决方法是使用非贪婪量词:*?
.或者不匹配每个字符,但匹配除逗号之外的所有字符:([^,]*)
.
Simple workaround is using non-greedy quantifier: *?
. Or match not every character, but all except comma: ([^,]*)
.
这篇关于Perl 中的模式匹配是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!