Suppose I have the following string:
Field1 = "Test"; Field2 = "Test"; Field3 = "Blah"; Field4 = "BlahBlah"
I am thinking of how I can write a regex expression I can use in .NET/C# where RegEx.IsMatch(...)
would return TRUE
if the value of Field1 = the value of Field2 and FALSE
otherwise. Can't think of a way to do this... Any ideas?
使用回引用 :
@"Field1 = (""\w+"");.*Field2 = \1"
as @ndn mentions, this is possible with backreferences, but trying to do this wholly within regex is like using the end of a screwdriver to pound in a nail. I think you'd be much better off parsing the whole thing with regex and using C# to analyze the results
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;
Note: in c# you have to escape "
by using ""
in a verbatim string (a string starting with @"
) and not \\"
as you would in a normal string.
Here is what the matches would look like in http://www.regexpixie.com
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.