-2

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);
        }
    }
}
Sri Reddy
  • 6,832
  • 20
  • 70
  • 112
  • Down vote for what? Appreciate if you give the reason so that I can improve my question. – Sri Reddy May 10 '16 at 19:53
  • This is a misuse of Regex. Regular Expressions can only be used to parse Regular Languages. The syntax of your data is not a regular langauge. The reason you can't use Regex to parse this data is the same reason why you can't use Regex to parse HTML. People can provide you with patterns that will match the sample data in your question, but those patterns are not going to always work for you with different data. You can see this question for a better explanation: https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not – Nick May 10 '16 at 20:10
  • @Nick We can't tell if his language is irregular just from the examples he gave. It could be a language consisting of only those two constructs. However, determining whether a regex is suitable or not should by done by its use cases. It should also be noted that modern regex engines exceed the boundaries of regular languages. – James Buck May 10 '16 at 21:22
  • @Nick, what if I always get my data in that format and those are the only two constructs that can be defined? I didn't state that in my question 'coz I thought the example were self explanatory. I will be careful from going forward. I agree with James on regex exceed the boundaries of regular languages and are used extensively for different simple or complex problems. – Sri Reddy May 10 '16 at 22:16
  • That will probably work for you then. If you had data where that "Id" string was not a string literal but came from some other property on another object like... `[SomeClass.Entity[SomeOtherClass.Entity["Id"]]]` then you'd start to have problems. – Nick May 11 '16 at 16:34

1 Answers1

1
\[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)
James Buck
  • 1,640
  • 9
  • 13