ChristianMurschall
ChristianMurschall

Reputation: 1711

.net regex optional named groups

I want to parse input strings looking like this: client/02004C4F4F50/box/registration client/02004C4F4F50/box/data/flow

with the .NET regex libary. client and box are always the same but the rest may differ. What I came up is this regex:

^client/(?<id>.+?)/box/(?<type>.+)(/(?<value>.+)?)

What I want is that registration and data are matched into the type group and that flow goes into an optional group value. It should look like this:

Groupname | Input 1      | Input 2
---------------------------------------
       id | 02004C4F4F50 | 02004C4F4F50
     type | registration | data
    value | {empty}      | flow

But with my current solution the optional group (value) is never matched. Perhaps someone has a hint.

Upvotes: 1

Views: 678

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can match subparts using [^/]+ pattern (any 1+ chars other than / char) and make the numbered capturing group rather than the value named capturing group optional, i.e. (/(?<value>.+)?) => (?:/(?<value>.+))? (also, you may turn the capturing group into non-capturing, or use (?n) inline ExplicitCapture modifier to make all capturing groups behave as non-capturing).

You may use

^client/(?<id>[^/]+)/box/(?<type>[^/]+)(?:/(?<value>[^/]+))?

See the regex demo

enter image description here

Upvotes: 1

Related Questions