Alternation
Alternation allows matching one of several phrases. This is more powerful than character classes, which are limited to characters.
Delimit the set of phrases with pipes—|.
/foo|bar|baz/g[RegExr] [Visual]- 2 matches
foo bazfoobaz
- 1 match
Your foodfoo
- 1 match
Behind barsbar
One of
foo,bar, andbaz
If only a part of the regex is to be “alternated”, wrap that part with a group—capturing or non-capturing.
/Try (foo|bar|baz)/g[RegExr] [Visual]- 1 match
Try fooTry foo
- 1 match
Try barTry bar
- 1 match
Try bazTry baz
- 1 match
Try foodTry foo
Tryfollowed by one offoo,bar, andbaz
Matching numbers between 100 and 250:
/1\d\d|2[0-4]\d|250/g[RegExr] [Visual]- 3 matches
100, 157, 199100157199
- 2 matches
139 + 140 = 279139140
- 1 match
201 INR201
- 1 match
$220220
- 1 match
250250
- 1 match
1250125
- 2 matches
e = 2.71828182...182182
- 0 matches
251 - 0 matches
729
This can be generalized to match arbitrary number ranges!
Examples
Hex colours
Let’s improve one of our older examples to also match shorthand hex colours.
/#([0-9A-F]{6}|[0-9A-F]{3})/g[RegExr] [Visual]- 1 match
#AE25AE#AE25AE
- 1 match
#663399#663399
- 1 match
How about #73FA79?#73FA79
- 1 match
Part of #73FA79BAC too#73FA79
- 1 match
#FFF#FFF
- 0 matches
#a2ca2c
It is important that [0-9A-F]{6} comes before [0-9A-F]{3}. Else:
/#([0-9A-F]{3}|[0-9A-F]{6})/g[RegExr] [Visual]- 1 match
#AE25AE#AE2
- 1 match
#663399#663
- 1 match
How about #73FA79?#73F
- 1 match
Part of #73FA79BAC too#73F
- 1 match
#FFF#FFF
- 0 matches
#a2ca2c
Tip
Regex engines try alternatives from the left to the right.
Roman numerals
/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/g[RegExr] [Visual]- 1 match
MMXXMMXX
- 1 match
VIVI
- 1 match
XXXX
- 1 match
XIXI
- 0 matches
IXI - 0 matches
VV