Regex Match Beginning of Line: Anchors and Multiline Mode
Anchors look simple: `^` for the start, `$` for the end. Two details make them subtler — the multiline flag redefines both, and `$` is more permissive than most people expect.
Default behaviour
Without flags, ^ matches only at the very start of the input and $ only at the very end. On multi-line input, ^Error will not match a line in the middle.
Anchors are zero-width: they assert a position and consume nothing, which is why ^^ is legal and pointless, and why ^ can appear inside alternations.
The multiline flag
With m (re.MULTILINE, RegexOptions.Multiline, Pattern.MULTILINE), ^ and $ match at every line boundary:
/^Error/ on "ok\nError: x" -> no match
/^Error/m on "ok\nError: x" -> matches line 2
This is what you want for log scanning and what you must avoid in validation — a multiline validator accepts input where only one line matches, which is a real bypass. ^\d{4}$ with m accepts "abc\n1234".
The trailing newline
In Python, Java, .NET and PCRE (PHP), $ also matches immediately before a final newline, so ^\d+$ accepts "123\n" — surprising when validating input from a textarea or a file read. JavaScript is the exception: without m, its $ means the very end, and /^\d+$/.test('123\n') returns false.
Use \z for the absolute end in Java, .NET and PCRE, where \Z means "end, allowing one trailing newline". Python is the odd one out: its \Z is already the absolute end, and \z was added as a synonym in Python 3.14. JavaScript has neither and does not need them, since its $ is already strict without m.
Similarly \A means the absolute start regardless of the multiline flag — safer than ^ in a validator that might later gain the flag.
Word boundaries are different
\b matches between a word character and a non-word character, so \bcat\b finds "cat" in "the cat sat" but not in "concatenate". It is a position, not a character.
Because \b is defined in terms of \w, it treats the underscore as a word character and every accented letter as a non-word character in ASCII mode — so \bcafé\b behaves unexpectedly without Unicode support enabled.
Frequently asked questions
What is the difference between ^ and \A?
^ can match at line starts when the multiline flag is on; \A always means the absolute start of the input.
Why does my anchored pattern accept a trailing newline?
Python, PHP, Java and .NET let $ match before a final newline; JavaScript does not. Anchor with \z (\Z in Python), or trim the input first.
Should validators use the multiline flag?
No. It lets input pass when only one line matches.