[英]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.