我对下面的正则表达式感到困惑。请帮助我理解它。
my $test = "fred andor berry";
if ($test =~ /fred (and|or) berry/) {
print "Matched!\n";
} else {
print "Did not match!\n";
}
我认为它会匹配,但我得到“不匹配!”。如果我添加
+
在里面,像这样,my $test = "fred andor berry";
if ($test =~ /fred (and|or)+ berry/) {
print "Matched!\n";
} else {
print "Did not match!\n";
}
然后它匹配。我以为我可以用
and|or
匹配带有“and”、“or”和“andor”的表达式。不?
最佳答案
正则表达式的一部分是 (and|or)
表示匹配“和”或“或”,但不能同时匹配。当您将加号附加到该组时,它可以匹配一次或多次。例如,“fred andandandand berry”也是 /fred (and|or)+ berry/
的有效匹配项。
关于regex - 使用 | 时两种选择是否匹配?在 Perl 正则表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265674/