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>.*))

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)

Leave a Reply