C#使用正则表达式在值中使用分隔符拆分名称值对字符串

C# Split namevaluepair string with delimitter in values using regex

我有一个字符串

"FirstName=John, LastName=Smith, Address=1 Wall Street, NY"

需要拆分成字典为:

考虑到地址字段值中包含分隔符 ',',如何使用 Regex 实现此目的?

也可以说我有以下字符串(注意地址中的冒号):

"FirstName=John, LastName=Smith, Address:1 Wall Street, NY"

如果= or :作为键值对分隔符,怎么会出现上述结果呢?

假设键不能包含任何分隔符(逗号后应跟键以分隔对)

var data = "FirstName=John, LastName=Smith, Address:1 Wall Street, NY, USA, TestKey=TestValue";
var dic = new Dictionary<string, string>();
var reg = @"([^=:,]*)[=:](.*?)(?:$|,\s*(?=[^=:,]*[=:]))";
foreach (Match m in Regex.Matches(data, reg)) {
    var key = m.Groups[1].Value;
    var val = m.Groups[2].Value;
    dic[key] = val;
    Console.WriteLine("{0} = {1}", key, val);
}