regex optional capture group

im having some problems with regex and optional groups.

I want to capture the following texts:

so i created this:

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


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

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

ive created a regex101 test case here:

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:


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

Leave a Reply