为什么^和$不能按预期工作? [英] Why do ^ and $ not work as expected?

查看:64
本文介绍了为什么^和$不能按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我困惑了最近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)$时,锚点将应用于整个组,因此它将匹配等于ab的字符串.

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.

此外,如果您确实不需要获取值,则可以使用

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.

这篇关于为什么^和$不能按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆