Possible to see on which regex is matched?

Viewed 73

Is it possible in C# to see on which Regex is matched?

So for example, if we have this Regex:

aaa[0-9]{2}\.zip|bbb[0-9]{2}\.zip

And we find bbb10.zip with the regex.

Is it then possible to see that the pattern that matched (it is bbb[0-9]{2}.zip)?

1 Answers

You may define a list of the patterns and build a pattern with alternatives wrapped in capturing groups. Then, once the match is found, you may loop through the groups and find the matched one.

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var p = new[] {
            @"aaa[0-9]{2}\.zip",
            @"bbb[0-9]{2}\.zip"
        };
        var pat = new Regex($"({string.Join(")|(", p)})");
        var match = pat.Match("We have bbb12.zip match");
        for (var n=1; n <= p.Count(); n++)
        {
            if (match.Groups[n].Success) 
            {
                Console.Write("{0} group matched, the pattern is {1}", n, p[n-1]);
                break;
            }
        }
    }
}

See the C# demo, output - 2 group matched, the pattern is bbb[0-9]{2}\.zip.

The regex will look like (aaa[0-9]{2}\.zip)|(bbb[0-9]{2}\.zip) where you clearly see two capturing groups.

Note that capturing group IDs start with 1, since match.Groups[0].Value is equal to match.Value, the whole match, that is why for loop starts with n=1.

Related