[英]What is the difference between /it/ and /\Ait\Z/
In Ruby both expressions seem to do similar things: 在Ruby中,两个表达式似乎都做类似的事情:
'it' =~ /^it$/ # 0
'it' =~ /\Ait\Z/ # 0
# but
/^it$/ == /\Ait\Z/ # false
So I an wondering what is the difference between ^
- \\A
and $
- \\Z
and how to choose which one to use? 所以我想知道
^
- \\A
和$
- \\Z
之间有什么区别,以及如何选择使用哪一个?
The difference is only important when the string you are matching against can contain new lines. 只有当您匹配的字符串可以包含新行时,差异才很重要。
\\A
matches the start of a string. \\A
匹配字符串的开头。 ^
matches either the start of a string or immediately after a new line. ^
匹配字符串的开头或紧跟新行之后。 Similarly \\Z
only matches the end of the string, but $
matches the end of the string or the end of a line. 类似地
\\Z
只匹配字符串的结尾,但$
匹配字符串的结尾或行的结尾。
For example, the regular expression /^world$/
matches the second line of "hello\\nworld" but the expression /\\Aworld\\Z/
fails to match. 例如,正则表达式
/^world$/
匹配“hello \\ nworld”的第二行,但表达式/\\Aworld\\Z/
无法匹配。
In regex engines that support multi-line regular expressions, ^
and $
are usually used for start and end of line markers. 在支持多行正则表达式的正则表达式引擎中,
^
和$
通常用于行标记的开始和结束。
\\A
and \\Z
are for start and end of string markers. \\A
和\\Z
用于字符串标记的开始和结束。
For example, the string: 例如,字符串:
Hello, my names
are Bob and James
would match ames$
twice (for names and James) but ames\\Z
only once (for James). 将匹配
ames$
两次(名字和詹姆斯),但ames\\Z
只有一次(詹姆斯)。
^
- start of line ^
- 行的开始
\\A
- start of string \\A
- 字符串的开头
$
- end of line $
- 行尾
\\Z
- end of string \\Z
- 字符串的结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.