Skip to content

What a pattern actually matches

A regex is a description of text, tried at every position until something fits.

Lesson 1 of 4 · about 3 minutes

A pattern is tried at every position

A regular expression is a small description of what some text looks like. The engine takes your description to the first character of the subject, asks "does the text from here match?", and if it does not, moves one character along and asks again. It stops at the first position where the whole pattern fits.

That one sentence explains most surprises. A pattern that seems to match "the wrong thing" is usually matching the earliest thing, because earliest wins over longest, and over whatever you had in mind.

Most characters describe themselves. The pattern cat matches the letters c, a, t in that order — inside "cat", and equally inside "concatenate". A regex has no idea what a word is unless you tell it.

The characters that mean something else

A dozen or so characters are instructions rather than literals: . \ | ( ) [ ] { } + * ? ^ $. A dot means "any character except a line break", not a full stop. To match a literal dot you escape it, \., and the same goes for the rest.

This is where a pattern that reads plausibly goes wrong. The pattern 3.14 matches "3.14", but it also matches "3x14" and "3914", because the dot is standing in for any character. Written as 3\.14 it means what it looks like.

Case, and why it is a flag rather than part of the pattern

Matching is case-sensitive by default. Rather than writing [Cc][Aa][Tt], you set the i flag and write cat. Flags sit outside the pattern because they change how the whole thing is read: i for case-insensitive, g to keep going after the first match instead of stopping, m to make anchors work per line.

Keep flags in mind when you copy a pattern from somewhere: the same pattern with and without g behaves differently in a replace, and that difference is invisible in the pattern itself.

Worked examples

  • Match a literal dot rather than any character

    /3\.14/

    Against: pi is 3.14, not 3x14

    Without the backslash this matches 3x14 too, which is the most common first regex bug.

  • Find a word regardless of case

    /cat/gi

    Against: Cat, cat, concatenate, CATALOGUE

    It matches inside concatenate and catalogue as well — a pattern has no concept of a word until you add one.

Check yourself

Practice questions written for this lesson — not past exam papers.

Practise every question in this subject

  1. What does the pattern a.c match?

  2. Why does searching for "cat" find something inside "concatenate"?

Try it