Regular Expression - Alternation and Branching
1. What is Alternation
Alternation refers to the use of a symbol in a regular expression | to represent the logical relationship of "or". It allows matching one of multiple possible patterns.
cat|dog
This pattern matches "cat" or "dog".
2. What is Branching
Branching refers to the regex engine attempting different matching paths when it encounters a choice point during matching. When one path fails to match, the engine backtracks and tries other possible paths.
Principle analysis
Alternation operator | working principle
- The regex engine scans from left to right
|each option separated by the operator - tries to match the first option, and stops if successful
- if the first option does not match, tries the second option
- and so on, until a match is found or all options have been tried
Grouping and alternation
Alternation is usually combined with grouping () to limit the scope of the alternation:
Example
gr
(
a
|
e
)
y
This pattern matches "gray" or "grey".
Branch backtracking mechanism
When the regex engine encounters a choice point:
- remember the current position (create a checkpoint)
- try the first branch
- if it fails, roll back to the checkpoint
- try the next branch
- repeat until success or all branches have been tried
Practical examples
Basic alternation example
Example
// Match multiple date formats
const
datePattern
=
/\b(January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}\b/
;
console.
log
(
datePattern.
test
(
"March 15, 2023"
)
)
;
// true
console.
log
(
datePattern.
test
(
"Sept 10, 2022"
)
)
;
// false (abbreviation does not match)
Grouped alternation example
Example
import
re
Match American or British spelling
pattern
=
r
"colou?r|color"
text
=
"The color is red and the colour is blue"
matches
=
re
.
findall
(
pattern
,
text
)
(
matches
)
Output: ['color', 'colour']
Complex branching example
Example
// Match multiple phone number formats
String
phonePattern
=
"(\(\d{3}\) ?|\d{3}[-.]?)\d{3}[-.]?\d{4}"
;
String
[
]
testNumbers
=
{
"(123)456-7890"
,
"123.456.7890"
,
"123-456-7890"
,
"1234567890"
}
;
for
(
String
number
:
testNumbers
)
{
System
.
out
.
println
(
number.
matches
(
phonePattern
)
)
;
// All output true
}
Extended applications
Performance optimization tips
-
Place high-frequency options first: place the most likely matching option at the front
(common|uncommon|rare) # optimization order 2.
Avoid redundant branches:
(a|ab|c) # 不好 (ab?|c) # 更好3.
Use non-capturing groups: when capturing the group is not needed
(?:pattern1|pattern2)
Practical Application Scenarios
- Log analysis: match multiple error message formats
- Form Validation: accept multiple valid input formats
- Text processing: find synonyms or variant spellings
- Route matching: URL routing in web frameworks