Regex tester · Guide

Regex Alternative Groups: Alternation and Group Capture

The pipe gives you alternatives, and combining it with groups is where two behaviours surprise people: alternation order decides the match, and a quantified group keeps only its last capture.

Alternation is first-match, not longest-match

The engine tries alternatives left to right and takes the first that allows the overall match to succeed — not the longest:

Regex
/cat|catalog/    on "catalog"   ->  matches "cat"
/catalog|cat/    on "catalog"   ->  matches "catalog"

Put longer or more specific alternatives first. This differs from POSIX engines such as grep, which use leftmost-longest — the same pattern can behave differently in grep -E and in Python.

Scope the alternation

The pipe has the lowest precedence, so it splits the entire pattern unless grouped:

Regex
/^cat|dog$/       # "starts with cat" OR "ends with dog"
/^(cat|dog)$/     # exactly "cat" or exactly "dog"
/^(?:cat|dog)$/   # same, without capturing

The first pattern is a very common validation bug — it accepts "catfish" and "hotdog".

A quantified group keeps only the last capture

(\w+,?)+ applied to a,b,c leaves group 1 holding only c. The group captured three times and each capture overwrote the previous one.

To collect every occurrence, match repeatedly instead of quantifying the group — matchAll in JavaScript, findall or finditer in Python, preg_match_all in PHP:

JavaScript
[...'a,b,c'.matchAll(/(\w+)/g)].map((m) => m[1]);   // ['a','b','c']

.NET is the exception: Group.Captures preserves every capture of a repeated group, which is occasionally exactly what you need and is not portable.

Character classes beat alternation

For single characters, a class is faster and clearer: [abc] rather than (?:a|b|c). The engine checks membership instead of trying three branches with backtracking.

Reserve alternation for multi-character alternatives, and factor out common prefixes where you can — re(?:ad|d) does less work than read|red.

Frequently asked questions

Why does my alternation match the shorter option?

Most engines take the first alternative that works, not the longest. Order the specific ones first.

Why does my group only hold the last value?

A quantified group overwrites its capture each repetition. Match repeatedly instead.

Is [abc] faster than (a|b|c)?

Yes. A character class is a membership test; alternation tries each branch.

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool