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
- 2 matches
foo baz
- 1 match
Your food
- 1 match
Behind bars
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
- 1 match
Try foo
- 1 match
Try bar
- 1 match
Try baz
- 1 match
Try food
Try
followed by one offoo
,bar
, andbaz
Matching numbers between 100 and 250:
/1\d\d|2[0-4]\d|250/g
- 3 matches
100, 157, 199
- 2 matches
139 + 140 = 279
- 1 match
201 INR
- 1 match
$220
- 1 match
250
- 1 match
1250
- 2 matches
e = 2.71828182...
- 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
- 1 match
#AE25AE
- 1 match
#663399
- 1 match
How about #73FA79?
- 1 match
Part of #73FA79BAC too
- 1 match
#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
- 1 match
#AE25AE
- 1 match
#663399
- 1 match
How about #73FA79?
- 1 match
Part of #73FA79BAC too
- 1 match
#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
- 1 match
MMXX
- 1 match
VI
- 1 match
XX
- 1 match
XI
- 0 matches
IXI
- 0 matches
VV