1

Here's a sample string:

Lorem ipsum dolor sit amet, ad eam option suscipit invidunt, ius propriae detracto cu. Nec te wisi lo{"firstName":"John", "lastName":"Doe"}rem, in quo vocent erroribus {"firstName":"Anna", "lastName":"Smith"}dissentias. At omittam pertinax senserit est, pri nihil alterum omittam ad, vix aperiam sententiae an. Ferri accusam an eos, an facete tractatos moderatius sea{"firstName":"Peter", "lastName":"Jones"}. Mel ad sale utamur, qui ut oportere omittantur, eos in facer ludus dicant.

Assume the following data model exists:

public class Person
{
   public string firstName;
   public string lastName;
}

How could I use regex to extract JSON out of this text and create a List<Person> with:

{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}

Objects can be buried anywhere in the string, so their position relative to words, letters, punctuations, whitespaces, etc. does not matter. If the above JSON notation is broken, simply ignore it. The following would be invalid:

{"firstName":"John", "middleName":"", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith", "age":""},
{"firstName":"Peter", "lastName":"Jones" some text}

In other words, pattern search must be strict to the following:

{"firstName":"[val]", "lastName":"[val]"}
5
  • Does it have to be a Regex? It might be easier to just do this with procedural code. Commented Jan 30, 2016 at 5:46
  • No, it doesn't have to be Regex. Just need to get it done. Commented Jan 30, 2016 at 5:47
  • You shouldn't use Regex with hierarchical data like JSON for the same reasons as XML Commented Jan 30, 2016 at 5:47
  • To Micky's point, is it legal to have nested JSON objects? I'd assume so, depending on where this is coming from. Or, equally frustrating, I assume you could have a string that contains a curly brace? Nobody would have a name with one, I assume, but it'd be totally valid JSON. Commented Jan 30, 2016 at 5:48
  • Nested objects aren't a concern at the moment. Ah, never thought about curly braces in the middle. I could instead use another symbol or substring and disallow the user from inputting it. Commented Jan 30, 2016 at 5:51

2 Answers 2

1

Here's a regex that you could use to extract the values:

({\s*"firstName":\s*"[^"]+",\s*"lastName":\s*"[^"]+"\s*})

After this, I'd suggest just using Json.NET to deserialize the objects.

Sign up to request clarification or add additional context in comments.

4 Comments

Just to clarify, is this simply (opening curly brace + any number of characters that are not closing curly brace + closing curly brace)? What if there was another opening curly brace in between? Also, firstName and lastName should be hard-coded.
This doesn't seem to return matches for me. Are the parentheses needed? Also, there is a space after the comma.
The parentheses are what returns the matches. The \s matches spaces. This is just the regex, you'll have to properly escape the backslashes and quotes in your C# string. Here's proof it is working: regex101.com/r/rO7bK2/1
Great. I was able to figure out escaping!
1

use this code snippet,

//Take All first Name
    string strRegex1 = @"firstName"":""([^""""]*)"",";
//Take All Last Name
    string strRegex2 = @"lastName"":""([^""""]*)""";
    Regex myRegex = new Regex(strRegex, RegexOptions.None);
   Regex myRegex2 = new Regex(strRegex2, RegexOptions.None);
    string strTargetString = @"{""firstName"":""John"", ""middleName"":"""", ""lastName"":""Doe""}," + "\n" + @"{""firstName"":""Anna"", ""lastName"":""Smith"", ""age"":""""}," + "\n" + @"{""firstName"":""Peter"", ""lastName"":""Jones"" some text}";

    foreach (Match myMatch in myRegex.Matches(strTargetString))
    {
      if (myMatch.Success)
      {
       // Add your code here for First Name
      }
    }

foreach (Match myMatch in myRegex2.Matches(strTargetString))
    {
      if (myMatch.Success)
      {
        // Add your code herefor Last Name
      }
    }

Comments

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.