Non-Capturing Groups
Group patterns for structure without creating numbered capture references.· 6 min
Concept
Non-capturing groups (?:...) group elements for quantifiers or alternation without adding a numbered capture. This keeps your capture group numbering clean.
When to use (?:...) instead of (...):
- You need grouping for alternation or a quantifier, but don't need to reference the captured text
- You want to avoid shifting capture group numbers when adding inner groups
- You're building patterns that other code will use — fewer captures means less confusion
Example: (?:https?|ftp):// groups the protocol options without capturing them, leaving group $1 available for something more meaningful.
/(?:https?|ftp)://[\w.-]+/gGroups the protocol as a non-capturing alternative — the URL host isn't shifted to group 2
/(?:very ){2,3}large/gMatches 'very very large' or 'very very very large' without capturing 'very '
Exercise
Write a pattern matching "colour" or "color" using a non-capturing group for the optional "u".
Your pattern: