正则表达式字符串开头/字符串结尾元字符的助记提示
众所周知,正则表达式的功能非常强大。但众所周知,语法有点尴尬。
例如,每次我使用它们时,我都会问自己 ^
和 $
中哪一个是字符串的开头(分别是结束字符串)元字符。
It is well known that regular expressions are powerful. But it is also known that the syntax is a bit awkward.
For example, each time I use them, I find asking myself which of ^
and $
is the start of string (respectively end of string) metacharacter.
I know that a quick google search or a simple cheat sheet may answer this, but yet I wonder if anyone knows a good mnemonic tip.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是我能想到的:从小事做起,大事做起。
This is what I can come up with: Starts small ends big.
我不知道这些锚点有什么帮助,但只要您对整个字符串进行操作并且不使用多行修饰符
m
(取决于您的正则表达式风格),您就可以在大多数情况下使用出于相同目的,口味\A
和\z
(或\Z
)。这些使用起来更直观,
A
是开始,Z
是结束。\A
输入的开头\Z
输入的结尾,但最后的终止符(如果有)\z
输入结束I don't know a help for those anchors, but as long as you operate on the whole string and don't use the multi line modifier
m
(depends on your regex flavor) you can use in most flavors\A
and\z
(or\Z
) for the same purpose.Those are more intuitive to use,
A
us the start andZ
is the end.\A
The beginning of the input\Z
The end of the input but for the final terminator, if any\z
The end of the input按字母顺序,
caret
位于dollar
之前。caret
comes beforedollar
alphabetically.答案很晚,但我刚刚与互联网上不同地方的人们谈论了完全相同的主题。这是我们迄今为止发现的内容。
那么,让我们从砖石类比开始。插入符号 (
^
) 看起来像屋顶。假设您首先建造屋顶,然后您获得报酬(获得$
)。同样,人们提到钱总是在最后出现,尽管有些人认为事实并非如此在一些黑手党生意中,所以这可能是一个令人困惑的助记符。 变化:« 您将收到以下付款结束»。
简单易记:«
^< /code> 看起来像一颗星星(t) »
。
Late answer but I just had a talk about the exact same subject with people in various place on the internet. Here is what we found so far.
So, let’s begin with a masonry analogy. The caret (
^
) looks like a house roof. So let’s say that first you build the roof, then you get paid (got the$
).Similarly, people mentioned that money always comes at the end, although some thought that it was not the case in some mafia business, so this is possibly a confusing mnemonic. Variation : « you will be paid in the end ».
A simple, easy to remember one: «
^
looks like a star(t) ».