Concept

Alternation with the | Operator

The pipe | matches either the expression on its left or on its right. Combine with groups to alternate over a subpattern.

Basic alternation

cat|dog matches the string 'cat' or the string 'dog.' The alternatives are tried left-to-right, and the first match wins. Alternation has the LOWEST precedence in regex — everything to the left of the | and everything to the right are treated as separate branches.

HTTP or HTTPS

Try this
/https?:///

Input

https://example.com

Result

Match: https://

File extensions

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

Input

photo.JPEG

Result

Match: .JPEG

Group to scope the alternation

Without parentheses, ^cat|dog$ means '^cat at the start OR dog$ at the end' — not what you'd expect. Wrap the alternatives: ^(cat|dog)$ matches either whole-string cat or whole-string dog.

Order affects what matches

Regex engines try branches left-to-right and stop at the first success. With 'cat|cats' on the input 'cats,' the engine matches 'cat' — the shorter branch wins because it comes first. Put longer/more specific alternatives first when that matters.

Wrong order — matches the shorter branch

Try this
/cat|cats/

Input

cats

Result

Match: cat

Right order — matches the longer branch

Try this
/cats|cat/

Input

cats

Result

Match: cats

When to prefer a character class

For single-character alternatives, [abc] is faster and clearer than (a|b|c). Use | for multi-character branches or when alternatives have different lengths.

Related patterns

All reference guidesOpen the RegexPro tester →