C.W.K.
Stream
Lesson 08 of 10 · published

Reading Regex — Slow Down, Group, Translate

~10 min · reading, decomposition

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The three-pass reading method

When you're handed a regex you didn't write, don't try to swallow it whole. Three passes, in order:

Pass 1: Find the anchors and groups. Look for ^, $, (...), (?:...), (?=...). These are the structural skeleton — they tell you the *shape* of the pattern.

Pass 2: Identify each character class and quantifier. What's being repeated? How many times? What set of characters? Translate each piece into English: [a-z]+ = "one or more lowercase letters."

Pass 3: Read the whole thing as one English sentence. If you can speak it, you understand it. If you can't, paste it into regex101 and read the explanation pane.

Worked example

Pattern: ^(\w+)\s+(\d{3,4})$

Pass 1 — anchors & groups: ^...$ means whole-string match. Two capturing groups separated by something.

Pass 2 — pieces: \w+ = one or more word characters. \s+ = one or more whitespace. \d{3,4} = three or four digits.

Pass 3 — sentence: "A line that is exactly: a word, then whitespace, then a 3-or-4 digit number. Capture the word as group 1 and the number as group 2."

Things to look up, not memorize

Some pieces appear rarely enough that you should look them up rather than memorize them: \p{...} Unicode categories, (?(name)yes|no) conditionals, (?>...) atomic groups. Knowing they exist is enough.

Code

Decomposing a real-world pattern·text
Pattern: ^([A-Z]{2})-(\d{4})-([A-Z0-9]{6})$

Pass 1 — structure:
  ^...$           whole-string match
  three groups separated by literal '-'

Pass 2 — pieces:
  [A-Z]{2}        exactly 2 uppercase letters
  -               literal hyphen
  \d{4}           exactly 4 digits
  -               literal hyphen
  [A-Z0-9]{6}     exactly 6 uppercase letters or digits

Pass 3 — sentence:
  "A code shaped like XX-1234-AB12CD: a 2-letter prefix,
   a 4-digit middle, a 6-character alphanumeric suffix."

External links

Exercise

Take this pattern: ^(?:https?:)?//([\w.-]+)(?:/([\w./-]*))?$ — apply the three-pass method on paper before pasting into a tester. Write your one-sentence translation, then verify against regex101's explanation. Score yourself.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.