[英]Regex Match Of Field Values Within a String
假设我有以下字符串:
Field1 = "Test"; Field2 = "Test"; Field3 = "Blah"; Field4 = "BlahBlah"
我在考虑如何编写可在.NET / C#中使用的regex表达式,如果Field1 的值 = Field2的值,则RegEx.IsMatch(...)
将返回TRUE
否则返回FALSE
。 无法想到一种方法...有什么想法吗?
使用回引用 :
@"Field1 = (""\w+"");.*Field2 = \1"
正如@ndn所提到的,使用反向引用是可行的,但是尝试完全在正则表达式中进行此操作就像使用螺丝刀的末端敲打钉子一样。 我认为使用regex解析整个内容并使用C#分析结果会更好
var matches = Regex.Matches(myInputString, @"
(?<fieldName>\w+)
\s*
=
\s*
""(?<value>[^""]+)""
;?", RegexOptions.IgnorePatternWhitespace);
//obviously what you do with the matches can get as complicated as you want
//but you have infinite flexibility now that you're in C#.
var field1Value = matches.Cast<Match>().FirstOrDefault(m => m.Groups["fieldName"].Value == "Field1").Value;
var field2Value = matches.Cast<Match>().FirstOrDefault(m => m.Groups["fieldName"].Value == "Field2").Value;
return field1Value == field2Value;
注意:在c#中,您必须在逐字字符串(以@"
开头的字符串)中使用""
而不是在普通字符串中使用\\"
来转义"
。
这是http://www.regexpixie.com中的匹配内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.