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 cho开发者_开发技巧ose 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
加载中,请稍侯......
精彩评论