.*
您编写正则表达式的方式无论是贪婪还是非贪婪都无关紧要。它仍然会匹配。
原因是您使用\b
了 between.*
和\w+
。
use strict;
use warnings;
my $string = 'this is a regular expression';
sub test{
my($match,$desc) = @_;
print '# ', $desc, "\n" if $desc;
print "test( qr'$match' );\n";
if( my @elem = $string =~ $match ){
print ' 'x4,'[\'', join("']['",@elem), "']\n\n"
}else{
print ' 'x4,"FAIL\n\n";
}
}
test( qr'^ (\w+) \b (.*) \b (\w+) $'x, 'original' );
test( qr'^ (\w+) \b (.*+) \b (\w+) $'x, 'extra-greedy' );
test( qr'^ (\w+) \b (.*?) \b (\w+) $'x, 'non-greedy' );
test( qr'^ (\w+) \b (.*) \b (\w*) $'x, '\w* instead of \w+' );
test( qr'^ (\w+) \b (.*) (\w+) $'x, 'no \b');
test( qr'^ (\w+) \b (.*?) (\w+) $'x, 'no \b, non-greedy .*?' );
# original
test( qr'(?^x:^ (\w+) \b (.*) \b (\w+) $)' );
['this'][' is a regular ']['expression']
# extra-greedy
test( qr'(?^x:^ (\w+) \b (.*+) \b (\w+) $)' );
FAIL
# non-greedy
test( qr'(?^x:^ (\w+) \b (.*?) \b (\w+) $)' );
['this'][' is a regular ']['expression']
# \w* instead of \w+
test( qr'(?^x:^ (\w+) \b (.*) \b (\w*) $)' );
['this'][' is a regular expression']['']
# no \b
test( qr'(?^x:^ (\w+) \b (.*) (\w+) $)' );
['this'][' is a regular expressio']['n']
# no \b, non-greedy .*?
test( qr'(?^x:^ (\w+) \b (.*?) (\w+) $)' );
['this'][' is a regular ']['expression']