C.W.K.
Stream
Lesson 04 of 12 · published

Conditional Patterns Revisited

~6 min · conditional, pcre

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

Beyond simple if-then-else

Track 4 introduced (?(N)yes|no). Advanced flavors extend this with named-group conditions and even lookaround conditions.

Lookaround condition

PCRE supports (?(?=lookahead)yes|no): "if the lookahead succeeds, match yes; otherwise match no." This lets you branch on "is the next thing X?" without consuming.

Named conditions

(?(name)yes|no) — branch based on whether named group matched. Same idea as numbered, but stable across edits.

The recursion-condition combo

The most powerful (and most cursed) use: combining recursion with conditionals. "If we're at depth N, do this; otherwise recurse." This is full Turing-tarpit territory.

When you actually need them

Almost never in production code. Most conditional logic reads better as alternation, post-processing, or — when truly complex — as a real parser.

The one legitimate use I've seen: validating a format that has "if X is present, Y must also be present" rules. Conditionals can express this in one regex; alternation requires duplication.

Code

Advanced conditional examples·python
import re

# Same as Track 4 but with named group
pattern = r'(?P<bracket>\()?\d+(?(bracket)\))'
bool(re.fullmatch(pattern, '(42)'))   # True
bool(re.fullmatch(pattern, '42'))     # True
bool(re.fullmatch(pattern, '(42'))    # False

# Conditional based on lookahead (PCRE-like, may not work in all engines)
# Match a number that is preceded by '$' XOR followed by ' USD'
# In Python this is hard; alternation is cleaner:
pattern = r'(?:(?<=\$)\d+|\d+(?= USD))'
re.findall(pattern, '$5 and 10 USD and 20')
# ['5', '10']

# Validation: 'if open paren, must close it' — alternation is cleaner
bool(re.fullmatch(r'\(\d+\)|\d+', '(42)'))  # True
bool(re.fullmatch(r'\(\d+\)|\d+', '42'))    # True
bool(re.fullmatch(r'\(\d+\)|\d+', '(42'))   # False

External links

Exercise

Pick a conditional regex pattern from any source (PCRE docs, Stack Overflow). Try to rewrite it with plain alternation. Compare the two: which would your future self understand faster?

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.