bflemi3
bflemi3

Reputation: 6790

c# Regex to match key value pairs

Given the following string

[ef:id =tellMeMore4, edit= yes, req=true,prompt = false]

I'm trying to match the edit key and value where the value can be yes, yesonce or no.

edit\s*=\s*(yes(once)?|no)

I'm getting back 3 groups:

{edit= yes}
{yes}
{}

Is there a way to match, meeting my requirements, but not have a group for the optional once value?

I tried this but it doesn't match properly on all variances:

edit\s*=\s*(yes[once]?|no)

Upvotes: 0

Views: 508

Answers (3)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51430

To specify you don't need to capture a group, use the (?: ... ) construct called a non-capturing group:

edit\s*=\s*(yes(?:once)?|no)

As a rule of thumb, always use the (?:...) construct instead of (...) unless you need to capture.

An alternative approach is to use named groups along with the RegexOptions.ExplicitCapture flag:

edit\s*=\s*(?<value>yes(once)?|no)

And of course, you can combine both approaches so you don't need the flag, but can keep the named capture:

edit\s*=\s*(?<value>yes(?:once)?|no)

The value is extracted with match.Groups["value"].Value.

Upvotes: 2

Ali Sepehri.Kh
Ali Sepehri.Kh

Reputation: 2508

Try this:

edit\s*=\s*\b(yesonce|yes|no)\b

Also you should use \b because you don't want to match yes or yesonce if the string is yesoncefunction .

Upvotes: 1

Morbia
Morbia

Reputation: 4344

this should work:

 edit\s*=\s*(yesonce|yes|no)

Upvotes: 0

Related Questions