Regex one or none

How the regex ? quantifier makes an element optional (zero or one), when to use it, how it differs from * and +, and pitfalls when copying patterns.

In regular expressions, "one or none" is the question mark quantifier. It means the element before it may appear once or not at all. This review explains what the quantifier changes, when it fits, and where it causes surprises. No tool-specific test results were supplied for this article. The behavior described here is the standard documented syntax of common regex engines, so confirm details against the engine you actually use.

Short answer: when the optional quantifier fits

Use ? when one well-defined piece of input may be present or absent, such as a spelling variant, an optional separator or an optional protocol suffix. Its main benefit is that a single pattern covers both variants. The tradeoff is that every optional part widens what the pattern accepts. That can include empty matches, and it means capture results may or may not have a value. A plain string comparison or a list of exact literals is the better choice when only two or three fixed strings are valid, or when the absent case needs different handling in your code.

What the question mark actually changes

Placed after a token, ? is equivalent to {0,1}. It changes the pattern, not the text: the input string is never modified, and only the set of strings that match is affected. The quantifier applies to the token immediately before it. That token can be a single character, an escape such as \d, a character class or a group.

colou?r        matches "color" and "colour"
https?://      matches "http://" and "https://"
\d{3}-?\d{4}   matches "555-1234" and "5551234"

Scope is the most common misreading. The pattern ab? means "a, followed by an optional b", not "an optional ab". To make a whole sequence optional, wrap it in a group: (?:ab)? if you don't need to capture it, or (ab)? if you do.

How one or none differs from other quantifiers

Quantifier | Meaning | Equivalent form
? | zero or one | {0,1}
• | zero or more | {0,}
• | one or more | {1,}
{n,m} | between n and m | none

Greedy, lazy and possessive forms

By default ? is greedy. It tries to include the element first and gives it up only if the rest of the pattern then fails. The lazy form ?? tries the zero case first and takes the element only if needed. The possessive form ?+ takes the element when it can and never gives it back. Possessive quantifiers are documented in PCRE, Java and Python 3.11 and later. JavaScript and .NET do not support them.

Pattern   Input   Match
ab?       ab      ab
ab??      ab      a
ab??c     abc     abc

The last row shows that laziness only changes the order in which options are tried. The lazy b first matches nothing, the following c then fails against "b", and the engine backtracks to include the b.

Other meanings of the question mark

Not every ? in a pattern is the one-or-none quantifier. Directly after an opening parenthesis it introduces special group syntax, such as (?:...) for non-capturing groups, (?=...) and (?!...) for lookaheads, and (?<name>...) for named groups in flavors that support them. After another quantifier, as in *?, +? or {2,5}?, it makes that quantifier lazy. To match a literal question mark, escape it as ? or put it in a class as [?]. Shell glob patterns use ? differently: there it means exactly one character, not an optional one.

Pitfalls that change what a pattern matches

  • A pattern made entirely of optional parts can match the empty string. ^\d?$ accepts empty input, and a global search for \d? in "abc" returns an empty match at each of its four positions.
  • An optional capturing group that did not take part in the match has no value. It is undefined in JavaScript and None in Python, so code that reads the group must handle that case.
  • Without anchors, a pattern can match inside a longer string. colou?r also finds "color" inside "colorful". Add ^ and $ or word boundaries when the whole input or a whole word must match.
  • Adjacent or nested optional elements that can consume the same characters create many ways to match the same text. In backtracking engines this can make failing matches slow, so keep optional parts distinct from their neighbors.

Will the pattern still work after copying it elsewhere?

Copying a regex raises a portability question. The ? quantifier is standard in PCRE, JavaScript, Python, Java, .NET and POSIX extended syntax. POSIX basic syntax is the exception: it is the default for grep and sed, and there ? is an ordinary character. GNU tools accept ? in basic syntax as an extension. Switching to extended syntax with -E is the more portable choice.

grep -E 'colou?r' notes.txt
grep 'colou\?r' notes.txt        # GNU basic syntax extension
sed -E 's/colou?r/color/g' notes.txt

Quoting adds another layer. In a shell, an unquoted ? is a glob wildcard, so put patterns in single quotes. Inside ordinary string literals in many languages, backslashes in tokens such as \d and ? must be doubled unless you use raw strings, such as Python's r"...", or regex literals, such as JavaScript's /.../. A pattern that works in a tester can fail after pasting because of this escaping layer even though the regex itself is correct.

Readability and reviewability

A single optional token is easy to read. A chain of optional groups is hard to audit. Free-spacing mode lets you split a pattern across lines and add comments. It is available as the x flag in PCRE, re.VERBOSE in Python, the COMMENTS flag in Java and IgnorePatternWhitespace in .NET. JavaScript has no equivalent flag, so long patterns there are easier to review if they are built from named parts or explained in nearby code comments.

A raw pattern is the wrong thing to show people who only need to know the rule. In documentation, validation hints and error messages, state the rule in plain words, for example "the hyphen in the phone number is optional". Dense symbol strings are hard to follow when scanned quickly or read aloud. No assistive-technology testing was supplied for this review, so this is general guidance rather than a measured result.

Testing a one-or-none pattern

  • Set the tester to the same flavor as your target engine, because group syntax and possessive support vary.
  • Test input with the optional part present and with it absent.
  • Test empty input and input where the optional part appears twice. For example, colou?r should not fully match "colouur" when anchored.
  • Check what each capture group returns when its optional part is missing.
  • Don't paste sensitive data into an online tester unless its data handling is documented.

Evidence and gaps

No product data, tester comparisons or benchmarks were supplied, so this article contains no measured results. The behavior described is documented regex syntax. Version-dependent features, especially possessive quantifiers, free-spacing flags and named-group syntax, should be checked against the documentation for the specific engine and version you deploy.