RegexBuilder
← Back to the tools
📦

Regex Groups and Alternation: (), (?:), | and Backreferences

Parentheses group parts of a pattern together and (by default) capture what they match. Alternation with | offers a choice. Together they let you build patterns from reusable pieces.

Capturing groups

(\d{3})-(\d{4}) matches 555-1234 and captures 555 and 1234 as two separate groups. Captured groups are how you extract parts of a match — the area code, the year, the price — for reuse in code or a replacement.

Non-capturing groups (?:…)

Sometimes you need the grouping but not the capture. (?:ab)+ repeats ab as a unit without creating a numbered group. Non-capturing groups are slightly faster and keep your capture numbers tidy.

Named groups

Instead of remembering that group 2 is the month, name it: (?<year>\d{4})-(?<month>\d{2}). Named groups make complex patterns far more readable and are supported in JavaScript, Python and PCRE.

Alternation with |

The pipe means "or". cat|dog matches either word. #([0-9a-f]{3}|[0-9a-f]{6}) matches a hex color with three or six digits. Wrap alternatives in a group so the | applies only where you want it.

Backreferences

A backreference matches the same text a group captured earlier. \b(\w+)\s+\1\b matches repeated words like "the the". In JavaScript and PCRE you write \1; named groups can be referenced as \k<name>.

Test and explain patterns free