Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regular Expression - Alternation and Branching

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

  1. The regex engine scans from left to right | each option separated by the operator
  2. tries to match the first option, and stops if successful
  3. if the first option does not match, tries the second option
  4. 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:

  1. remember the current position (create a checkpoint)
  2. try the first branch
  3. if it fails, roll back 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: 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

  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