Lessons · Regex · ?: there or not
Zero or one
? after a token or group makes it optional: zero or one of it. colou?r matches color and colour; (ab)?c matches c and abc.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Spelling variants, an optional country code, a trailing s: the difference between a pattern that works on all your data and one that works on half of it.
How to think about it
Find the piece that is sometimes there, wrap it in a group if it is more than one character, and put ? after it. Check both forms match, and that the pattern does not now match something you did not intend.
Worked example
pattern: colou?ru is optional.
text: color and colourBoth spellings match.
pattern: (ab)?cThe whole group ab is optional.
text: c abcBoth match: plain c, and abc.
pattern: https?://http or https.
text: http://a and https://bBoth.
Your turn
Match dog or dogs.
dogs
Test a pattern against real text
The trap
? has a second meaning after another quantifier: .*? is lazy, not optional. Where it sits decides what it means.