为什么^和$不能按预期工作?
这让我困惑了最近15分钟:
This puzzled me the last 15 minutes:
if ('ab' =~ /^a|b$/) { print 't' } else { print 'f' }
print "\n";
我期望开头和结尾处的"a"或"b"只能匹配一个字符.因此,对于两个字符"ab",测试应失败.但是成功了.为什么?
I have expected that 'a' or 'b' following the beginning and followed by the end, should match only one character. So the test should fail for two characters 'ab'. But it succeeds. Why?
如果将交替分组,那么您将获得预期的行为:
If you group the alternation, then you will get the expected behavior:
/^(a|b)$/
您的正则表达式将在字符串的开头(带有^a
分支)找到a
,或者在字符串的结尾(带有b$
分支)找到b
.
Your regex will find a a
at the start of the string (with ^a
branch) or b
at the end (with the b$
branch).
使用^(a|b)$
时,锚点将应用于整个组,因此它将匹配等于a
或b
的字符串.
When you use ^(a|b)$
, the anchors are applied to the whole group and thus it will match a string that is equal to a
or b
.
此外,如果您确实不需要获取值,则可以使用 n
修饰符,/^(a|b)$/n
.
Also, if you do not really need to capture the value, you may either use a non-capturing group, /^(?:a|b)$/
, or a n
modifier, /^(a|b)$/n
.