Alex Gao Alex Gao - 2 months ago 6
Python Question

If there difference between `\A` vs `^` (caret) in regular expression?

Python's

module documentation says:


^
: (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

\A
: Matches only at the start of the string.


Is there any difference when using them?

Answer

Both of these match:

re.search('^abc', 'abc')
re.search('\Aabc', 'abc')

This also matches:

re.search('^abc', 'firstline\nabc', re.M)

This does not:

re.search('\Aabc', 'firstline\nabc', re.M)