There is a string like

Protocol = (SNMP) Address = (\ (test \))

Is it possible to break it into pairs key \ value, what would happen ^

Protocol - SNMP;

Adress - \ (test \)

The main problem is that the partition follows the first occurrence of the closing bracket ")". Ie getting out

\ (test \

How to prevent the occurrence of such a screened character?

    2 answers 2

    You can use the negative view forward .

    (?!\)) - check if there is a closing bracket in front.

     string input = @"Protocol=(SNMP) Address=(\(test\))"; string pattern = @"(?<key>\w+) = \( (?<value>.+?) \) (?!\))"; var matches = Regex.Matches(input, pattern, RegexOptions.IgnorePatternWhitespace); foreach (Match match in matches) { Console.WriteLine(match.Groups["key"].Value); Console.WriteLine(match.Groups["value"].Value); Console.WriteLine(); } 
    • It would be better to check the absence of a backslash no one bothers to write addr=(abc\(test\)x\(y\)z) then there is only a problem with checking the shielding of the reverse slash itself, but if the vehicle has no real data in the real data, then it can and will stop so as not to overload the regular season - Mike

    If the string format is precisely defined (there is no variable number of spaces, extra characters before / before = , ( , ) , etc.), then regular expressions can be dispensed with. At the very least, this will give a performance boost.

     var str = @"Protocol=(SNMP) Address=(\(test\))"; string[] values = str.Split(' '); var result = new Dictionary<string, string>(); foreach (var v in values) { string[] pairs = v.Split('='); result[pairs[0]] = pairs[1].Substring(1, pairs[1].Length - 2); } 
    • Plus Using multiple string.Split or Regex.Split often the easiest way. - Alexander Petrov