Search code examples
regexregex-group

Capture optional Group


I want to capture the values of some keys which may be optional, specifically consider the string below

@Foo1:dog|a=5|b=6|c=10|d=12|e=2
@Foo2:cat|a=12|c=10|d=11|e=123
@Foo1:bat|a=213123|b=10
@Foo3:pet|c=346

Now I want to capture the strings between @ and :, : and |, and the value of keys b, d which may be optional. I should the following captured

Foo1, dog, 6, 12
Foo2, cat, 11
Foo1, bat, 10
Foo3, pet

I am using this regex ^@(\w+):(\w+).*(?:b=(\d+)).*(?:d=(\d+)) but it only works when both b and d are present.


Solution

  • You may use

    ^@(\w+):(\w+)(?:.*?\|b=(\d+))?(?:.*?\|d=(\d+))?
    

    See the regex demo

    Details

    • ^ - start of string
    • @ - a @ char
    • (\w+) - Group 1: one or more word chars
    • : - a colon
    • (\w+) - Group 2: one or more word chars
    • (?:.*?\|b=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |b= and then capturing 1+ digits into Group 3
    • (?:.*?\|d=(\d+))? - an optional non-capturing group matching any 0+ chars other than line break chars, as few as possible, then |d= and then capturing 1+ digits into Group 4