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

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

问题描述

这在过去的 15 分钟让我感到困惑:

This puzzled me the last 15 minutes:

if ('ab' =~ /^a|b$/) { print 't' } else { print 'f' }
print "
";

我预计开头和结尾的 '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 分支)或在末尾(带有 bb$ 分支).

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.

此外,如果您真的不需要捕获该值,您可以使用 非捕获组/^(?:a|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.

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

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