Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex – Identically Named capture groups during an OR

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Move the optional phrase outside the capture:

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

See live demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading