Tuesday, June 28, 2011

C# Find matching parenthesis in string

Tuesday, June 28, 2011 Posted by Unknown , , ,
I needed a way to parse a JSON array in separate json objects. The difficult thing is the parameter matching. I found a way to do it on msdn:
string twitter = @"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=broersa&count;=20&include;_rts=1";
string json = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(twitter) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  // Get the response stream
  using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    json = reader.ReadToEnd();
Regex regex = new Regex("{[^{}]*(((?{)[^{}]*)+((?})[^{}]*)+)*(?(Open)(?!))}");
MatchCollection m = regex.Matches(json);

This gives a nice collection of the separate JSON objects.

You can use this on anglebrackets or braces by replacing the curlybraces with other  characters.