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 optional capture group

im having some problems with regex and optional groups.

I want to capture the following texts:
"role:subrole.net"

so i created this:
(?<Role>.*)(\:(?<SubRole>.*))(\.(?<net>.*))

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

and that seems to work just fine.

however when i try to make the "SubRole" and the "net" optional i can not get it to work, ive tried various things like

(?<Role>.*)(\:(?<SubRole>.*)?)(\.(?<net>.*)?)

and at first it still captures all 3 texts, but if i then just test with

"role:subrole", "role.net" or "role" it will not caption anything

ive created a regex101 test case here: https://regex101.com/r/OMyOe1/1

what am i missing? thanks in for your time and insight..

>Solution :

You should place the ? for the "zero or one occurrence) outside the group with the : respectively . at the start, otherwise you have to specify the : even if you don’t have one of the optional groups to match:

^(?<Role>[^:.]*)(?::(?<SubRole>[^\n.]*))?(?:\.(?<net>.*))?$

(I also incorporated and extendend the hint of @Wiktor Stribiżew to get matches for only role, role.net or role:subrole)

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