简体   繁体   English

匹配集合正则表达式模式

[英]Match Collection Regex Pattern

I'm trying to figure out the Regex Pattern to get the "displayName" and "id" from my body of text. 我正在尝试找出正则表达式模式,以从我的正文中获取“ displayName”和“ id”。 ( a json object). (一个json对象)。

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. 这是我正在使用的Regex模式和代码。

  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 Alpha,患者,0-50FCF5!16077 Beta,患者,0-50FCF5!16077

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. 但是,实际上,如果您的文本是JSON,那么正确的JSON解析器可能会给您更令人满意的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM