Hone

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?r
u is optional.
text: color and colour
Both spellings match.
pattern: (ab)?c
The whole group ab is optional.
text: c abc
Both match: plain c, and abc.
pattern: https?://
http or https.
text: http://a and https://b
Both.

Your turn

Match dog or dogs.

dogs

The trap

? has a second meaning after another quantifier: .*? is lazy, not optional. Where it sits decides what it means.

Practise ?: there or not on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.