Hone

Lessons · Regex · alternation (or)

This or that

a|b matches either. Its scope is everything on each side, so group it: gr(a|e)y.

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

Yes/no answers, several file extensions, a list of allowed words.

How to think about it

What are the alternatives, and what applies to all of them? Put alternatives in a group so anchors and neighbours apply to all of them: ^(yes|no)$.

Worked example

pattern: \.(png|jpg|gif)$
Ends with one of three extensions.
text: photo.jpg
Match.
text: photo.jpeg
No match.

Your turn

Match cat or dog as whole words.

\b(catdog)\b

The trap

^yes|no$ means 'starts with yes' OR 'ends with no'. The group is not optional.

Next in Regex

Every Regex lesson on one page

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