我对下面的正则表达式感到困惑.请帮我理解一下.
my $test = "fred andor berry";
if ($test =~ /fred (and|or) berry/) {
print "Matched!\n";
} else {
print "Did not match!\n";
}
Run Code Online (Sandbox Code Playgroud)
我认为它会匹配,但我得到"不匹配!".如果我加入+它,像这样,
my $test = "fred andor berry";
if ($test =~ /fred (and|or)+ berry/) {
print "Matched!\n";
} else {
print "Did not match!\n";
}
Run Code Online (Sandbox Code Playgroud)
然后匹配.我以为我可以使用and|or"and","or"和"andor"来匹配表达式.没有?
cft*_*nas 11
正则表达式的一部分(and|or)意味着匹配'和'或'或'但不是两者.将加号附加到该组后,它可以匹配一次或多次.例如,"fred andandand berry"也是一个有效的匹配/fred (and|or)+ berry/
虽然人们倾向于读a|b作“a 或 b”,但|它不是 OR 运算符;它是交替运算符。它为当时可以匹配的内容指定了一组备选方案。更准确的读法是“'a' 或'b'(但不是两者)”。
当你写的时候,(and|or)+你添加了+量词,意思是“一个或多个前面的原子”。其效果是,它不会匹配可以是“and”或“or”的单个值,而是匹配一系列值,每个值都可以是“and”或“or”。它将匹配以下所有内容:
and
or
andor
orand
andorand
andandorororandorandand
Run Code Online (Sandbox Code Playgroud)
如果你真的只想匹配“and”、“or”和“andor”(虽然我不知道你为什么想要),你可以这样写:
(and|or|andor) # capture
(?:and|or|andor) # don't capture
Run Code Online (Sandbox Code Playgroud)
取决于您是否要捕获匹配的特定值。(Plain(...)创建一个捕获分组。(?:...)创建一个非捕获分组。)
| 归档时间: |
|
| 查看次数: |
4933 次 |
| 最近记录: |