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

  1. The regular expression engine scans|from left to right through the alternatives separated by |
  2. Tries to match the first alternative; if successful, stops
  3. If the first alternative does not match, tries the second alternative
  4. 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

gr(a|e)y

This pattern will match "gray" or "grey".

Branching and Backtracking

When the regular expression engine encounters an alternation point:

  1. Remember the current position (create a checkpoint)
  2. Try the first branch
  3. If it fails, backtrack to the checkpoint
  4. Try the next branch
  5. 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)
print(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

  1. Place high-frequency options first: Put the most likely matching option at the front

    (common|uncommon|rare)  # 优化顺序
  2. Avoid redundant branches:

    (a|ab|c)  # 不好
    (ab?|c)   # 更好
  3. Use non-capturing groups: when capture groups are not needed

    (?:pattern1|pattern2)

Real-World Application Scenarios

  1. Log analysis: Match multiple error message formats
  2. Form validation: Accept multiple valid input formats
  3. Text processing: Find synonyms or variant spellings
  4. Route matching: URL routing in web frameworks
Other Extensions