In Ruby both expressions seem to do similar things:
'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?
The difference is only important when the string you are matching against can contain new lines. \\A
matches the start of a string. ^
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.
For example, the regular expression /^world$/
matches the second line of "hello\\nworld" but the expression /\\Aworld\\Z/
fails to match.
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.
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).
^
- start of line
\\A
- start of string
$
- end of line
\\Z
- end of string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.