简体   繁体   中英

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)

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 .

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 .

这应该工作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM