Home > Enterprise >  Regex - Identically Named capture groups during an OR
Regex - Identically Named capture groups during an OR

Time:08-31

I have two scenarios and I want to capture both alternatives using a specific named group.

Scenario 1 - The apple falls far from the tree Scenario 2 - The really mighty splendid big apple falls far from the tree

Is there a way to capture the fruit in both scenarios without using a lot of question marks and have it fall under the same named group?

The following works but only using two different group names:

The (?:(?P<Fruit1>apple)|really mighty splendid big (?P<Fruit2>apple)) falls far from the tree\s?

https://regex101.com/r/Ouiziy/1

CodePudding user response:

Move the optional phrase outside the capture:

The (?:really mighty splendid big )?(?P<Fruit>apple) falls far from the tree\s?

See live demo.

  • Related