[英]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: 我回来了3组:
{edit= yes}
{yes}
{}
Is there a way to match, meeting my requirements, but not have a group for the optional once
value? 有没有一种方法可以满足我的要求,但没有一个可选的
once
值分组?
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: 另一种方法是将命名组与
RegexOptions.ExplicitCapture
标志一起使用:
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
. 使用
match.Groups["value"].Value
提取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
. 你也应该使用
\\b
,因为你不想匹配的yes
或yesonce
如果字符串是yesoncefunction
。
这应该工作:
edit\s*=\s*(yesonce|yes|no)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.