Denis
Denis

Reputation: 12087

Regex Match Of Field Values Within a String

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?

Upvotes: 1

Views: 660

Answers (2)

viggity
viggity

Reputation: 15237

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

enter image description here

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36110

Use back references:

@"Field1 = (""\w+"");.*Field2 = \1"

Upvotes: 3

Related Questions