0

I'm trying to use System.Text.RegularExpressions.Regex class to grab some text from a JSON string. The sting is something like

[{"name":"joe","message":"hello","sent":"datetime"}{"name":"steve","message":"bye","sent":"datetime"}]

I'm attempting to use the Matches() method to grab the "message" values. However, specifying a match as something like message":"*","sent as the pattern would return 3 matches:

hello
bye
hello","sent":"datetime"}{"name":"steve","message":"bye

How do I structure the options or modify my pattern to exclude recursive regex checks? I only want matches

hello
bye
4
  • 4
    You may want to address why you're using a RegEx instead of one of the numerous tried-and-true JSON libraries and snippets available in C#. Commented Oct 12, 2012 at 1:24
  • I would recommend using JSON.NET, this is not a good application for RegEx. You can download the package through NuGet in Visual Studio or it can be found here; nuget.org/packages?q=Json.NET Commented Oct 12, 2012 at 1:27
  • Is that really the regex you used? I don't see how it would return those matches. Should * have been .*? Commented Oct 12, 2012 at 2:33
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Oct 12, 2012 at 3:00

2 Answers 2

1

The JavaScriptSerializer class (namespace System.Web.Script.Serialization, assembly System.Web.Extensions.dll) is pretty useful for dealing with JSON strings like this.

var json = "[{\"name\":\"joe\",\"message\":\"hello\",\"sent\":\"datetime\"},{\"name\":\"steve\",\"message\":\"bye\",\"sent\":\"datetime\"}]";

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<object[]>(json);

// now have an array of objects, each of which happens to be an IDictionary<string, object>
foreach(IDictionary<string, object> map in result)
{
    var messageValue = map["message"].ToString();
    Console.WriteLine("message = {0}", messageValue);
}
Sign up to request clarification or add additional context in comments.

Comments

1

JSON is better parsed by a JSON tool.

You can try using the non-greedy syntax .*? for example.

3 Comments

I couldn't figure out how to use the Json.net DeserializeObject method - Here is what I have so far: string[] messages = new string[NumberOfMessages]; for(int i = 0; i < messages.GetUpperBound(0); i++) { messages[i] = JsonConvert.DeserializeObject<string>(; }
Note sure how to structure the <>() after DeserializeObject for a string... Thanks you everyone for their input!
@Zach: I would recommend posting another question if you want to know about how to use a Json tool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.