How a pattern is read: precedence and grouping

Beginner · 9 min

A regex has an order of operations: escapes, groups, quantifiers, concatenation, then alternation. Learn it, then build a pattern in tested steps.

Before thisQuantifiers: star, plus and questionCounted repetitionAnchors and line boundariesAlternation

Kris Jordan · 12 min · from 2:53

How a pattern is read: precedence and grouping

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

Taught by Kris JordanReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Order of operations, tightest first: escapes, groups and classes, quantifiers, concatenation (one thing after another), then alternation |.
  • So ab+ repeats only the b, (?:ab)+ repeats the pair, abc|def is (abc)|(def), and ^a|b$ is not ^(a|b)$.
  • Parentheses override the order exactly as in arithmetic. Use (?:...) when you only need grouping and don't want a numbered capture.
  • Build a pattern in small steps and test each against should-match and should-not-match lists. Each step's failing case tells you what to add next.
  • When composing a pattern from strings or .source values, wrap an alternation in (?:...) first, or the | takes over the whole result.

A pattern is a tiny expression tree

In arithmetic, 2 + 3 * 4 is 14 and not 20 because multiplication binds tighter than addition. Nobody tells the calculator where the brackets go. Regex works the same way. A pattern is not read strictly left to right, and the engine has a fixed order of operations. From tightest to loosest:

  1. Escapes and atoms: \., a literal, a class like [a-z].
  2. Groups: ( ... ) and (?: ... ).
  3. Quantifiers: * + ? {n,m}, each applying to the one item just before it.
  4. Concatenation: one thing after another, with no symbol between them.
  5. Alternation: |, the loosest.

The later lessons in the roadmap fill in the details of groups. Here the point is only what those five levels mean for a pattern you write today.

Reading it in practice

Run these patterns against a handful of strings and the levels become visible (Y means a match):

              ab   abab abb  abbb cd   acd  abd  a*
/^ab+$/       Y    -    Y    Y    -    -    -    -
/^(?:ab)+$/   Y    Y    -    -    -    -    -    -
/^ab|cd$/     Y    Y    Y    Y    Y    Y    Y    -
/^(?:ab|cd)$/ Y    -    -    -    Y    -    -    -
/^a(?:b|c)d$/ -    -    -    -    -    Y    Y    -
/^a\*$/       -    -    -    -    -    -    -    Y
  • ab+: the quantifier is tighter than concatenation, so it binds to b only. abb and abbb pass and abab doesn’t.
  • (?:ab)+: parentheses override. The pair repeats, so abab passes and abb fails.
  • ^ab|cd$: alternation is loosest, so this is ^ab or cd$. abab matches because it starts with ab, and acd because it ends in cd. Neither is “exactly ab or cd”.
  • ^(?:ab|cd)$: wrap the choice and the anchors apply to both.
  • a(?:b|c)d: the group scopes the bar to a single letter, so it accepts abd and acd.
  • a\*: the escape binds tightest. It is a literal star, and only the string a* passes.

Concatenation takes no symbol, which makes it easy to forget it’s an operator. abc|def splits on the bar and nothing else: it behaved identically to (?:abc)|(?:def) on abc, def, abdef, abcdef and ab. It did not behave like ab(?:c|d)ef, which is a different language.

Building a pattern in steps

The way to write a pattern that works is to grow it, testing at each step. This is the harness from the testing lesson, run on dates with an optional time, using three strings that should match and six that shouldn’t:

should match:     "2026-03-14"  "2026-03-14 09:30"  "2026-03-14T09:30:15"
should not match: "2026-3-14"  "2026-03-14 9:30"  "2026-03-14T09"
                  "2026-03-14 09:30:"  "x2026-03-14"  "2026-03-14Z"

Step 1, the date alone, /\d{4}-\d{2}-\d{2}/, found everything it should but also five strings it shouldn’t (2026-03-14 9:30, 2026-03-14T09, 2026-03-14 09:30:, x2026-03-14 and 2026-03-14Z). It matches inside longer text. Fix: add anchors.

Step 2, /^\d{4}-\d{2}-\d{2}$/, has no false hits now, but it missed both strings with a time. Fix: add an optional group for the time, using a class [T ] for the separator.

Step 3, /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2})?$/, missed only 2026-03-14T09:30:15. Fix: an optional seconds group inside the time group.

Step 4, /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?)?$/ printed ok: every wanted string matched and every unwanted one was rejected. Each step used a quantifier on a group, which is where precedence matters: (?:...)? makes the whole time optional, and (?::\d{2})? nests inside it.

Notice what this pattern still accepts: 2026-13-45. A regex checks shape, not meaning, which the later lessons on dates and validation return to.

Composing pieces

Long patterns are easier to keep correct if you name the parts. JavaScript has no verbose mode, but you can join pieces with template strings and .source:

const date = /\d{4}-\d{2}-\d{2}/.source, hm = /\d{2}:\d{2}/.source, sec = /:\d{2}/.source;
const full = new RegExp(`^${date}(?:[T ]${hm}(?:${sec})?)?$`);
full.source === /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?)?$/.source   // true

Precedence is the catch when you compose. A piece that contains a bare | swallows its neighbours:

const alt = /cat|dog/.source;
new RegExp("^" + alt + "$").test("catfish")        // true
new RegExp("^(?:" + alt + ")$").test("catfish")    // false

The first version is ^cat|dog$ all over again. Wrap any piece with a bar in (?:...) before you insert it.

About the video

The embed is a clip of Kris Jordan’s “Regular Expression OR Operator and Operator Precedence (aka the Alternation Operator)”, published on 17 May 2020 and 11 minutes 53 seconds long. The clip plays from 2:53 to the end, covering his chapters “Operator precedence in regex”, “Grouping with parentheses”, “Solving the robbery mystery” and “Advanced precedence and conclusion”. The description says the OR operator has lower precedence than the “and then” operator, and that parentheses can control the order of operations “just like you do in algebraic expressions”. That matches this lesson closely, and it is the same analogy. It does not mention quantifiers, and I couldn’t read a transcript, so I don’t know whether the video places them in the order above. The step-by-step build is mine. English per its title and description.

What I did not run

GNU grep, regex101, and the order of operations in flavours other than JavaScript. I checked the precedence claims only in Node 26.

Next

You can now read a pattern as a tree and build one in tested steps. The next group starts with the parentheses themselves, and what they remember: Grouping with parentheses.

Check yourself

  1. 01In which order does a regex apply its operators?

    Escapes first, then groups, then quantifiers, then concatenation, and alternation last. Quantifiers bind tighter than concatenation, and | binds loosest.

  2. 02Why does /^ab|cd$/ match 'abd' and 'acd'?

    | is lowest, so the pattern is ^ab or cd$. 'abd' starts with ab and 'acd' ends with cd. Use /^(?:ab|cd)$/ to require the whole string to be ab or cd.

  3. 03Your date pattern /\d{4}-\d{2}-\d{2}/ accepts 'x2026-03-14' and '2026-03-14Z'. What is the first fix?

    Anchor it: /^\d{4}-\d{2}-\d{2}$/. Nothing stopped the match from sitting inside a longer string.

  4. 04You build new RegExp('^' + /cat|dog/.source + '$'). What goes wrong, and how do you fix it?

    The bar splits the result into ^cat and dog$, so 'catfish' matches. Wrap the inserted piece: new RegExp('^(?:' + source + ')$').

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