Skip to main content
Regexflux
Lesson 4 of 120 completed

Anchors

Match positions in a string rather than characters, for precise boundary control.· 6 min

Concept

Anchors match positions in a string, not actual characters:

- ^ — matches the start of the string (or start of each line with the m flag) - $ — matches the end of the string (or end of each line with the m flag) - \b — word boundary: the position between a word character and a non-word character - \B — non-word boundary: any position that is NOT a word boundary

Anchors are zero-width — they don't consume any characters. They just assert that the match happens at a particular position.

Example: ^Error matches "Error" only at the very start of the string. \.js$ matches ".js" only at the end.

/^\d/g

Matches a digit at the very start of the string

123abc
4 items
abc123
42
/\.json$/g

Matches .json only at the end of the string

config.json
data.json.bak
package.json
json.config
/\bcat\b/g

Matches the word "cat" but not as part of another word

the cat sat
concatenate
wildcat species
my cats are

Exercise

Write a pattern that matches strings starting with a digit (using the `^` anchor).

Your pattern:

Must match

1 item
42 apples
0 errors
9 lives

Must not match

abc123
hello 5
42
no digits