Skip to content

Alternation and order

Leftmost, not longest

The first branch that works wins, however short it is.

| separates alternatives, and the engine tries them strictly in the order written. The first branch that lets the rest of the pattern succeed is the one that wins — not the longest, not the best.

So cat|catalogue can never match catalogue when it is free to stop early, and swapping the two branches changes what the pattern matches. Branch order is a correctness decision, not a style one.

Anchors hide this. With ^…$ around the alternation the engine is forced to backtrack into the later branch, so both orders give the same answer and the bug waits until somebody removes the anchors.

| binds looser than everything else, so it splits the whole pattern unless you group it. ^a|b$ is (?:^a)|(?:b$) — a string starting with a, or a string ending with b. It is almost never what was meant.

Matcher

Every claim on the left has a pattern under it. Press one and it runs here, against the same engine that grades a task.