[英]Extracting specific JSON out of large string using C# Regex
這是一個示例字符串:
Lorem ipsum dolor就座,ad eam選項suscipit invidunt,iuspropriae detracto cu。 {nc te wisi lo {“ firstName”:“ John”,“ lastName”:“ Doe”} rem,以錯誤的形式出現{{firstName“:” Anna“,” lastName“:” Smith“} dissentias。 在Omittam Pertinax感官上,pri nihil alterum omittam ad,即vix aperiam sententiae an。 費里(Ferri)指責某人,是多面的tractatos moderatius sea {“ firstName”:“ Peter”,“ lastName”:“ Jones”}。 Mel廣告銷售utamur,qui utportere 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]"}
這是一個可用來提取值的正則表達式:
({\s*"firstName":\s*"[^"]+",\s*"lastName":\s*"[^"]+"\s*})
在這之后,我建議僅使用Json.NET對對象進行反序列化。
使用此代碼段,
//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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.