user2268507
user2268507

Reputation:

Determine which groups matched in regex

In my program, I have a regex pattern as follows:

pattern = "([\\w ]+)(\\d{4})\\s*(?:720|480|1080)[pP]|([\\w ]+)(\\d{4})|([\\w ]+)";
Match match = Regex.Match(filename, pattern);

pattern contains 3 different or conditions with each condition containing 2,2 and 1 matching group(s) respectively.

Is there a way I can determine which condition has matched and hence which group to retrieve?

Thank you for your help.

Upvotes: 1

Views: 77

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391306

The group object has a Success property that is relevant in this scenario:

Here is some code that demonstrates:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var re = new Regex("((?<a>a)|(?<b>b))");

        var ma = re.Match("a");
        Console.WriteLine("a in a: " + ma.Groups["a"].Success);
        Console.WriteLine("b in a: " + ma.Groups["b"].Success);

        ma = re.Match("b");
        Console.WriteLine("a in b: " + ma.Groups["a"].Success);
        Console.WriteLine("b in b: " + ma.Groups["b"].Success);
    }
}

This will output:

a in a: True
b in a: False
a in b: False
b in b: True

.NET Fiddle

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

If you don't really care which format the input is in among the 3 formats, rewrite your regex like this to combine all 3 branches:

"([\\w ]+)(?:(\\d{4})(?:\\s*(?:720|480|1080)[pP])?)?"

And your data can be retrieved from capturing group 1 and 2.

The order of trial is preserved, due to the default greedy property of quantifier.

Upvotes: 0

Related Questions