Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between /it/ and /\Ait\Z/

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?

like image 387
Dmytrii Nagirniak Avatar asked Oct 13 '10 06:10

Dmytrii Nagirniak


2 Answers

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.

like image 169
Mark Byers Avatar answered Sep 27 '22 03:09

Mark Byers


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).

like image 26
paxdiablo Avatar answered Sep 26 '22 03:09

paxdiablo