Optional with ?
The ? quantifier makes the preceding item optional (zero or one): colou?r matches color and colour. To make a whole sequence optional, group it: (?:-\d{4})? matches an optional dash plus four digits. A ? placed after another quantifier (*?, +?) means lazy, not optional.
Syntax
x? (?:abc)? (abc)?Examples
"color colour colouur".match(/colou?r/g)Result: ["color", "colour"]
["12345", "12345-6789"].map(s => /^\d{5}(?:-\d{4})?$/.test(s))Result: [true, true]
The whole -NNNN part is optional.
"https://a.com http://b.com".match(/https?:\/\/\S+/g)Result: ["https://a.com", "http://b.com"]
Only the s is optional.
"call 555-1234".match(/(\d{3}-\d{4})(?: ext (\d+))?/)Result: ["555-1234", "555-1234", undefined]
When the optional group does not participate, its capture is undefined.
Common mistakes
- Writing abc? when you mean (?:abc)?: only the c is optional.
- Reading a capture from an absent optional group and getting undefined; check before using it.
- Confusing x+? (lazy) with (?:x+)? (optional).
- Making the first item optional and then testing with .test, which happily matches the empty string; anchor the pattern or require something.
Practice Optional with ?
These drills check your answer on live data, free, no account needed.
- Optional letter: color or colourThe whole line must match. Match the American spelling color and the British spelling colour only.
- Optional group: phone extensionThe whole line must match. Match a number like 555-0142, optionally followed by a space, ext, a space and 1 to 4 digits.
- US ZIP and ZIP+4The whole line must match. Match a five-digit ZIP code, optionally followed by a hyphen and four more digits.
Questions
How do I make a character optional in regex?
Put ? after it: colou?r. For a character class, [,.]? makes an optional comma or period.
How do I make a group optional?
Wrap it and add ?: (?:ext \d+)? for a non-capturing optional group, (ext \d+)? if you need the text.
What is the regex for optional whitespace?
\s* (zero or more). Use \s? only when at most one whitespace character is allowed.
Related
- QuantifiersWhat * + ? {n} {n,} and {n,m} mean, how greedy matching works, how to repeat a group instead of a single character, and the silent {2, 3} mistake.
- Non-capturing group (?:...)How (?:...) groups for quantifiers and alternation without a numbered capture, why that keeps group numbers stable, and how it changes findall in Python.
- Lazy vs greedyHow greedy quantifiers overshoot, how adding ? makes them lazy, why a negated class is often better than .*?, and the performance and newline traps.
- Regex for ZIP codeZIP code regex for US 5-digit and ZIP+4 formats, plus patterns for UK, Canadian and German postal codes, with examples and the common anchoring mistake.
Previous: Negated character classNext: Ranges in character classes