pattern?
是贪婪的,如果你想让它不贪婪,你必须说pattern??
:
#!/usr/bin/perl
use strict;
use warnings;
my $test = "'some random string'";
if($test =~ /\'?(.*?)\'?/) {
print "Captured [$1]\n";
print "Matched [$&]\n";
}
if($test =~ /\'??(.*?)\'??/) {
print "Captured [$1]\n";
print "Matched [$&]\n";
}
来自 perldoc perlre:
识别以下标准量词:
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
默认情况下,量化的子模式是“贪婪的”,也就是说,它会尽可能多地匹配(给定一个特定的起始位置),同时仍然允许模式的其余部分匹配。如果您希望它匹配尽可能少的次数,请在量词后面加上“?”。请注意,含义不会改变,只是“贪婪”:
*? Match 0 or more times
+? Match 1 or more times
?? Match 0 or 1 time
{n}? Match exactly n times
{n,}? Match at least n times
{n,m}? Match at least n but not more than m times