简体   繁体   中英

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"] .

Here is what I tried so far. I am missing the last ] . The result of my code is Entity["Id" .

Also, the input string could be [url]/XYZ/[SomeClass.EntityId] . It should give result of EntityId then.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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