Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions: difference between ^ and \A

Tags:

regex

Is the only difference between ^ and \A the fact that \A can never match after a line break? (even in multi-line mode)

The PCRE man page says:
^      assert start of string (or line, in multiline mode)
...
\A     matches at the start of the subject

Thanks!

like image 474
mikewaters Avatar asked Oct 26 '10 04:10

mikewaters


2 Answers

Yes. \A will match at the very beginning of your value. ^ will match the beginning of the value, but will also match immediately after newlines in multiline mode (//m).

The \Z is similar, but with the end of the value. However, it will also match before a newline at the end of the value. If you don't want this behaviour, use \z, which matches only at the end of the value.

Useful reference: perlre manpage

like image 62
Tim Avatar answered Oct 13 '22 01:10

Tim


If you have this as your target or subject string:

Line 1\n
Line 2\n
Line 3\n

The regex /^Line/gm will match all three lines. The ^ anchor matches at the first part of the string or after a logical CR/LF if the /m flag is present.

The regex /\ALine/gm will only match the first line no matter what. The \A assertion only matches at the absolute beginning of the target or subject string regardless of the /m flag.

like image 33
dawg Avatar answered Oct 13 '22 00:10

dawg