GROUPS & ALTERNATION

Non-capturing groups

Use `(?:...)` to bundle a sub-pattern without capturing it.

A plain group (...) does TWO jobs at once. It bundles a sub-pattern so a quantifier or | applies to all of it, AND it captures - it remembers the text it matched into a numbered slot you can reuse later as $1, $2, and so on.

Often you only need the bundling. `(?:...)` is a group that bundles WITHOUT capturing. Same grouping power, but it stores nothing and takes no slot number. The ?: right after the open paren is what turns capturing off.

Why bother? It keeps your capture numbers clean. Say you want the area code and the number from a phone like "212-555". With a throwaway wrapper, (?:\+1 )?(\d{3})-(\d{4}), the parts you care about stay $1 (area code) and $2 (number). Make that wrapper a plain group, (\+1 )?(\d{3})-(\d{4}), and everything shifts: now the optional prefix is $1, the area code is $2, the number is $3. The (?:...) keeps the numbering stable and signals "grouping only" to anyone reading the pattern.

Functionally (?:ab)+ and (ab)+ match the same text - this playground checks the match, not the capture slots, so both pass the drill. The difference bites the moment you start numbering groups, which is the very next lesson.

PRACTICE - 2 DRILLS 0/2 DONE
DRILL 1/2

Match one or more repetitions of "ab" or "cd" back to back. Bundle the alternation in a non-capturing group.

/ /
ababcd done
must match: "ababcd"
cd ab cdcd
must match: "cd" "ab" "cdcd"
xyz
must match nothing
DRILL 2/2- Greeting

Match "hello" or "hi" followed by " there", bundling the alternation in a non-capturing group.

/ /
hello there friend
must match: "hello there"
hi there, hello there
must match: "hi there" "hello there"
hey there
must match nothing