使用C#Regex从大字符串中提取特定JSON

时间:2016-01-30 05:41:18

标签: c# json regex

这是一个示例字符串:

  

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”,   “姓氏”: “史密斯”} dissentias。在omittam pertinax senserit est,pri   nihil alterum omittam ad,vix aperiam sententiae an。 Ferri accusam an   eos,facete tractatos moderatius sea {“firstName”:“Peter”,   “姓氏”: “琼斯”}。 Mel ad sale utamur,qui ut oportere omittantur,   eos in facer ludus dicant。

假设存在以下数据模型:

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

我如何使用正则表达式从本文中提取JSON并使用以下内容创建List<Person>

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

对象可以埋在字符串中的任何位置,因此它们相对于单词,字母,标点符号,空格等的位置无关紧要。如果上面的JSON表示法被破坏,只需忽略它。以下内容无效:

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

换句话说,模式搜索必须严格遵守以下规定:

{"firstName":"[val]", "lastName":"[val]"}

2 个答案:

答案 0 :(得分:0)

这是一个可以用来提取值的正则表达式:

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

在此之后,我建议只使用Json.NET反序列化对象。

答案 1 :(得分:0)

使用此代码段,

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