Hone

Lessons · Regex · which alternative wins

The first branch that works, wins

Alternation takes the FIRST alternative that matches at the earliest position, not the longest one.

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

Two alternatives that share a prefix are common -- cat and category, int and integer, 3 and 3.5 -- and the order decides the answer.

How to think about it

Longest first. It is a one-line rule that avoids the whole class of bug, and it costs nothing when the alternatives are unrelated.

Worked example

re.search(r'cat|category', 'category').group()
The first branch matched, so the second was never tried.
re.search(r'category|cat', 'category').group()
Reordered, and now it takes all of it.
re.search(r'\d+|\d+\.\d+', '3.5').group()
The same rule losing you the decimal part.

Your turn

Match the whole word 'category', not just 'cat'.

re.search(r'|cat', 'category').group()

The trap

It is ordered, not greedy about branches. The engine is not comparing them and picking a winner; it stops at the first that works.

Practise which alternative wins on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.