简体   繁体   中英

Extracting specific JSON out of large string using C# Regex

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]"}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM