C# Split namevaluepair string with delimitter in values using regex

I have a string

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

which needs to be split into a dictionary as:

  • {"FirstName", "John"}
  • {"LastName", "Smith"}
  • {"Address", "1 Wall Street, NY"}

How can this be achieved using Regex considering Address field value has the delimiter ',' in it?

Also lets say I have the following string (note the colon in Address):

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

How can the above mentioned result be with either = or : acting as the key value pair separator?

Answers


Assuming keys cannot contain any of delimeters (comma should be followed by key to separate pairs)

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);
}

Need Your Help

jQuery Ajax return variable (logic flaw)

javascript jquery ajax

I have been trying to learn Javascript/jQuery but I have hit a wall that I can't seem to break.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.