Trey Balut
Trey Balut

Reputation: 1395

Match Collection Regex Pattern

I'm trying to figure out the Regex Pattern to get the "displayName" and "id" from my body of text. ( a json object).

Here is the source:

  "value": [
    {
        "displayName": "Alpha,Patient",
        "id": "0-50F!16077"
    },
    {
        "displayName": "Beta,Patient",
        "id": "0-50F!16078"
    },
    {
        "displayName": "Beta6,Pateint",
        "id": "0-50F!12035"
    },
    {
        "displayName": "Delta,Patient",
        "id": "0-50F!16399"
    },

And here is the Regex Pattern and code I'm using.

  string regularExpressionPattern1 = "\\{(.*?)\\},";
        Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
        MatchCollection collection = regex.Matches(body.ToString());

        string tempStr=collection[0].Groups[1].ToString();

        foreach(Match m in collection)
        {
            string[] tempArray = m.Value.ToString().Split(',');
        }

Escaping the curly braces was the best I could come up with.

I would like my collection to look like:

Alpha,Patient , 0-50FCF5!16077 Beta,Patient , 0-50FCF5!16077

Upvotes: 0

Views: 435

Answers (1)

asherber
asherber

Reputation: 2713

It's not pretty, but if you have to use a regex, and you're sure what the text looks like:

var re = new Regex(@"(?s)displayName"": ""(?<name>.+?)"",.*?id"": ""(?<id>.+?)""");

foreach (Match match in re.Matches(text))
{
    Console.WriteLine($"displayName = {match.Groups["name"]} | id = {match.Groups["id"]}");
}

// displayName = Alpha,Patient | id = 0-50F!16077
// displayName = Beta,Patient | id = 0-50F!16078
// displayName = Beta6,Pateint | id = 0-50F!12035
// displayName = Delta,Patient | id = 0-50F!16399

But really, if your text is JSON, then a proper JSON parser will probably give you more satisfactory results.

Upvotes: 1

Related Questions