简体   繁体   English

C# regex.Match 返回带有第二个方括号的数据(如果存在)

[英]C# regex.Match to return data with second square brackets if it exist

How to include second square brackets in my match result.如何在我的比赛结果中包含第二个方括号。 If I have regex like如果我有正则表达式

\\[msg.(?<msgfield>.*?)\\]

My input string is我的输入字符串是

[url]/XYZ/[SomeClass.Entity["Id"]]

Then how to get the result match of Entity["Id"] .那么如何获取Entity["Id"]的结果匹配。

Here is what I tried so far.这是我到目前为止所尝试的。 I am missing the last ] .我错过了最后一个] The result of my code is Entity["Id" .我的代码的结果是Entity["Id"

Also, the input string could be [url]/XYZ/[SomeClass.EntityId] .此外,输入字符串可以是[url]/XYZ/[SomeClass.EntityId] It should give result of EntityId then.然后它应该给出EntityId结果。

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        String sample = "[url]/XYZ/[SomeClass.Entity[\"Id\"]]";
        Regex regex = new Regex(@"\[SomeClass.(?<msgfield>.*?)\]");

        Match match = regex.Match(sample);

        if (match.Success)
        {
            Console.WriteLine(match.Groups["msgfield"].Value);
        }
    }
}
\[SomeClass\.(?<msgfield>[^]]+\]?)\]

Regex demo.正则表达式演示。

A few things:一些东西:

  • Use a negated character set instead of .*?使用否定字符集而不是.*? inside the capturing group捕获组内
  • Escape the .逃离. character to make it a literal match instead字符使其成为文字匹配
  • Match the ] inside the capturing group (if present)匹配捕获组中的] (如果存在)

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

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