Regular Expressions - Alternation and Branching
1. What is Alternation
Alternation means using|in a regular expression to represent the logical relationship "or". It allows you to match one of multiple possible patterns.
cat|dog
This pattern will match "cat" or "dog".
2. What is Branching
Branching means that when the regular expression engine encounters an alternation point during matching, it tries different matching paths. When one path fails, the engine backtracks and tries other possible paths.
Principle Analysis
The alternation operator|How it works
- The regular expression engine scans
|from left to right through the alternatives separated by | - Tries to match the first alternative; if successful, stops
- If the first alternative does not match, tries the second alternative
- And so on, until a match is found or all alternatives have been tried
Grouping and Alternation
Alternation is often combined with grouping()to limit the scope of the alternation:
Example
This pattern will match "gray" or "grey".
Branching and Backtracking
When the regular expression engine encounters an alternation point:
- Remember the current position (create a checkpoint)
- Try the first branch
- If it fails, backtrack to the checkpoint
- Try the next branch
- Repeat until success or all branches have been tried
Practical Examples
Basic Alternation Example
Example
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
# 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)
print(matches) # Output: ['color', 'colour']
Complex Branching Example
Example
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: Put the most likely matching option at the front
(common|uncommon|rare) # 优化顺序
Avoid redundant branches:
(a|ab|c) # 不好 (ab?|c) # 更好
Use non-capturing groups: when capture groups are not needed
(?:pattern1|pattern2)
Real-World 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