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

The Golden Rule of Regex

~8 min · principle, philosophy

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

One rule, end of track

Regex is the smallest tool that solves a shape problem. Use it when the question is about shape. Reach for a parser the moment the question becomes about structure.

Everything else in this quest is implementation. The ten lessons of this track gave you the mental model:

  1. Regex describes shapes of text — not structure, not meaning.
  2. It lives in every text-touching tool you already use.
  3. Most of a pattern is just literal characters; only 14 are special.
  4. An engine compiles your pattern into a state machine and walks the input.
  5. Different flavors exist; the 80% is portable.
  6. Always build patterns in a tester first.
  7. Use verbose mode or composition — readability beats cleverness.
  8. Read by structure first, characters second.
  9. Don't try to parse with regex; reach for a real parser.
  10. Use the smallest tool that does the job.

What's next

From here, the quest goes mechanical: character classes (Track 2), quantifiers (Track 3), groups and alternation (Track 4), zero-width assertions (Track 5), language-specific APIs (Track 6), real-world patterns you'll lift directly into your code (Track 7), and the advanced features that separate journey-level from senior (Track 8).

Every later track loops back to the principles you just learned. When you're stuck, come back to this lesson. The ten ideas above will outlast any specific syntax you memorize.

Code

The whole quest, in one example·python
import re

# A real-world example using almost everything from this quest:
# - literal characters
# - character class
# - quantifier
# - capturing groups
# - anchors
# - VERBOSE for readability

ORDER_LINE = re.compile(r'''
    ^                          # start of line
    (?P<date>\d{4}-\d{2}-\d{2})  # ISO date
    \s+                        # whitespace
    (?P<order>\#\d+-\d+)       # order number like #42-1138
    \s+\$                      # currency
    (?P<amount>\d+\.\d{2})     # decimal price
    $                          # end of line
''', re.VERBOSE | re.MULTILINE)

for m in ORDER_LINE.finditer(orders_text):
    print(m.groupdict())

External links

Exercise

Write the simplest possible regex that solves a real problem you have today. Bonus points if it's under 30 characters and reads in one English sentence. That's the standard the rest of the quest is calibrating you toward.

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.