0

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

Trey Balut
  • 1,355
  • 3
  • 19
  • 39
  • 4
    consider using a json parser... – Daniel A. White Jan 24 '18 at 02:30
  • 2
    Consider [`JsonConvert.DeserializeObject()`](https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm) method instead of parsing manually by regex patterns. – Tetsuya Yamamoto Jan 24 '18 at 02:39
  • Use Regex named group is another option. See reference [here](https://stackoverflow.com/questions/906493/how-do-i-access-named-capturing-groups-in-a-net-regex). – Anna Jan 24 '18 at 02:48
  • Solved problem. Do not parse JSON the [Cthulhu way](https://blog.codinghorror.com/parsing-html-the-cthulhu-way/). – wp78de Jan 24 '18 at 02:56

1 Answers1

1

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.

asherber
  • 2,508
  • 1
  • 15
  • 12