Anchors and line boundaries

Beginner · 14 min

^ and $ match positions, not characters. Start and end of string versus line, the m flag, JavaScript's missing \A and \z, and Python's trailing-newline trap.

Before thisLiterals and escapingCharacter classesShorthand classes

Wendi Jollymore · 39 min · from 24:23

Anchors and line boundaries

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Wendi JollymoreReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • ^ and $ are anchors: they match a position (start or end of the text) and consume no characters. Replacing /^/ with '>' inserts a character without removing any.
  • Without the m flag, ^ and $ mean start and end of the whole string. With m they match at every line start and line end.
  • Validate a whole value with both anchors. /\d{3}/ finds three digits anywhere. /^\d{3}$/ demands exactly that. With the m flag, /^\d+$/ accepts '42\nanything'.
  • JavaScript has no \A or \z: /\Aabc/ matches the text 'Aabc'. Python has \A and \Z, Perl has \A, \z and \Z, and Python 3.9 has no \z.
  • In Python and Perl, $ also matches just before a trailing newline, so re.search(r'^\d+$', '42\n') succeeds. JavaScript's does not. Use \Z in Python, \z in Perl, or fullmatch.

Where, not what

Every pattern so far matched characters. Sometimes the question is not what but where. “Is this entire input a number?” is different from “is there a number somewhere in this input?”. Consider /\d+$/:

/^\d+$/.test("42")          // true
/^\d+$/.test("42 apples")   // false
/\d+$/.test("apples 42")    // true

The pattern ^\d+$ says: start of the text, one or more digits, end of the text. Nothing else may appear, so 42 apples fails. The symbols ^ and $ are anchors. They don’t match a character. They match a position, a place between characters (or at either edge of the text), and they consume nothing. You can see that by using them in a replacement:

"abc".replace(/^/, ">")    // ">abc"
"abc".replace(/$/, "<")    // "abc<"

The engine matched the empty spot before a, replaced zero characters with >, and nothing was lost. The same pair in sed gives the familiar prefix and suffix idioms: sed -E 's/^/> /' printed > one and > two, and s/$/ </ printed one < and two <.

String versus line

By default ^ and $ refer to the whole input, whether it is one word or a thousand lines. Add the m flag (multiline) and they refer to every line:

const t = "one\ntwo\nthree";
t.match(/^\w+/g)          // [ 'one' ]
t.match(/^\w+/gm)         // [ 'one', 'two', 'three' ]
t.match(/\w+$/gm)         // [ 'one', 'two', 'three' ]
t.replace(/^/gm, "> ")    // "> one\n> two\n> three"

The flag name is confusing, but the effect is simple: it is about where the anchors can match, and it does nothing to the dot (that is the s flag from the last lesson). Python’s equivalent is re.M, and grep and sed work line by line, so their anchors are always line anchors: printf 'a\n\nb\n\n' | /usr/bin/grep -c '^$' printed 2, counting the empty lines.

One more detail: JavaScript treats \r as a line break for the m flag, so /a$/m.test("a\r\nb") was true. In Python, re.search(r"a$", "a\r\nb", re.M) was falsy, because Python only counts \n. Files from Windows can therefore behave differently by language.

The validator hole

The m flag creates a classic security bug. You validate input with a whole-value pattern, someone adds m to “make it work for multi-line”, and the check stops checking:

/^\d+$/.test("42\nanything")    // false
/^\d+$/m.test("42\nanything")   // true

With m on, $ matches at the end of the first line, so the digits-only rule passed on a value that has more text after the newline. For validation of a single value, leave m off.

Absolute anchors and the trailing newline

What if you want “the very start” and “the very end” even in multi-line mode? Some flavours have dedicated anchors. JavaScript is not one of them, and it fails quietly. \A is not an error without the u flag, just a literal letter:

/\Aabc/.test("Aabc")   // true
/\Aabc/.test("abc")    // false

With the u flag it throws Invalid escape. Python offers \A (start) and \Z (end), Perl offers \A, \z (very end) and \Z. In Python 3.9, \z is an error: bad escape \z at position 3.

There’s a second Python and Perl surprise. Their $ matches at the end or just before a final newline:

Python:  re.search(r"^\d+$", "42\n")      True
         re.search(r"^\d+\Z", "42\n")     False
         re.fullmatch(r"\d+", "42\n")     False
Perl:    "42\n" =~ /^\d+$/ 1   /^\d+\z/ 0   /^\d+\Z/ 1   "42" =~ /\A\d+\z/ 1
JS:      /^\d+$/.test("42\n")             false

So a Python ^\d+$ validator accepts "42\n", which is awkward when a value came from input() or a file read. In Perl, \z is strict and \Z allows the newline, and the Python spelling \Z is the strict one, so the same two letters mean different things. Use re.fullmatch or \Z in Python and \z in Perl. In JavaScript the plain $ is already strict without m: /^\d+$/.test("42\n") was false, and with m it turned true.

Anchors inside a larger pattern

An anchor can sit anywhere, but it only matches where the position really is a start or end. /a^b/.test("a^b") is false, and /\n^b/ fails on "a\nb" until you add the m flag, which makes it true. The common place for surprise is alternation: ^a|b$ anchors a to the start and b to the end separately, not both together. The precedence lesson works through that.

About the video

The embed is a clip of Wendi Jollymore’s “Basic Regular Expressions 3 - Quantifiers and Anchors”, published on 18 April 2022 and 38 minutes 52 seconds long. The clip plays from 24:23 to 38:16 and covers her chapters “Anchors - Starts With”, “Multiline Flag”, “Anchors - Ends With”, “Both Anchors Together” and an exercise. Her description names regexr as the tester. I couldn’t read a transcript, so I can’t say whether she covers the validator hole, \A and \z, or the trailing newline, and I expect those come from this page only. English per its title and description.

What I did not run

GNU grep and regex101. I did not test \r\n input beyond the one JavaScript and one Python case shown.

Next

Anchors pin a position at an edge. Word boundaries are the same kind of zero-width test, but sit between a word and a non-word character.

Check yourself

  1. 01What does 'abc'.replace(/^/, '>') return, and why does nothing disappear?

    '>abc'. The anchor matches the empty position before the first character and consumes nothing, so the replacement is simply inserted.

  2. 02What do ^ and $ match in JavaScript with the m flag?

    The start and end of every line, not just of the whole string. 'one\ntwo\nthree'.match(/^\w+/gm) returns all three words, while without m it returns only 'one'.

  3. 03Why is /^\d+$/m a poor input validator?

    With the m flag the anchors match at line boundaries, so '42\nanything' passes because its first line is all digits. Drop m, or check the whole string.

  4. 04How do you require a Python string to be digits only, with no trailing newline allowed?

    Use re.fullmatch(r'\d+', s) or the pattern \A\d+\Z. The pattern ^\d+$ accepts '42\n' because Python's $ matches before a final newline.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark