appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Groups, alternation and capturing

Lesson 3 of 39 minBeginner

Combine options, capture parts of a match and reuse them.

Parentheses group parts of a pattern and capture what they match. The pipe | means "or".

cat|dog                      # cat or dog
(Mr|Ms)\.? \w+              # Mr Smith, Ms. Lee
(\d{4})-(\d{2})-(\d{2})     # captures year, month and day of 2026-10-04

Captured groups can be reused in replacements. In JavaScript, "2026-10-04".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1") gives 04/10/2026.

Non-capturing and named groups

  • (?:...) groups without capturing.
  • (?<year>\d{4}) names a group (supported in JavaScript, Python as (?P<year>...), and others).

Flags

  • i ignore case.
  • g find all matches (JavaScript).
  • m make ^ and $ match at each line.

A word on email validation

NoteA simple pattern like ^[^@\s]+@[^@\s]+\.[^@\s]+$ catches obvious typos. The only real way to validate an email is to send a message to it.

CarefulBadly written patterns with nested quantifiers, such as (a+)+$, can take exponential time on some inputs (ReDoS). Keep patterns simple and avoid running untrusted patterns.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does cat|dog mean?
2. What does a pair of parentheses do besides grouping?
3. What does the i flag do?
4. Why can (a+)+$ be dangerous?

Key terms