How-to

How to Match Multiple Patterns (Alternation)

Combine patterns with | to match either option. Wrap alternatives in a group to scope the alternation correctly.

The pipe operator

cat|dog|fish matches any of the three words. The engine tries each branch in order, left to right, and returns the first match. Alternation has the lowest precedence in regex, so everything to the left of | is one complete alternative and everything to the right is another.

Any common image extension

Try this
/\.(jpg|jpeg|png|gif|webp|svg)$/i

Input

photo.PNG

Result

Match: .PNG

Always group alternations when nesting

^red|blue|green$ does NOT match 'red,' 'blue,' and 'green' as whole strings — it matches '^red,' OR 'blue,' OR 'green$.' Wrap: ^(red|blue|green)$ to anchor the alternation correctly.

Wrong — anchors apply to only the first/last branch

Try this
/^red|blue|green$/

Input

blueberry

Result

Match: blue (unexpected!)

Right — grouped alternation

Try this
/^(red|blue|green)$/

Input

blueberry

Result

No match

Order matters for overlapping alternatives

The engine stops at the first matching branch. If one branch is a prefix of another, put the longer one first, or use word boundaries. 'cat|cats' matches 'cat' on the input 'cats' — the engine picks the shorter branch because it comes first.

When a character class is a better fit

[abc] is a faster and clearer way to say 'a, b, or c' when the alternatives are single characters. Reach for | when at least one alternative is multi-character.

Related patterns

All reference guidesOpen the RegexPro tester →