Reputation: 2639
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]"}
Upvotes: 1
Views: 744
Reputation: 854
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.
Upvotes: 1
Reputation: 635
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
}
}
Upvotes: 1