简体   繁体   中英

Using a regex with 'or' operator and getting matched groups?

I have some string in a file in the format

rid="deqn1-2"  
rid="deqn3"  
rid="deqn4-5a"  
rid="deqn5b-7"  
rid="deqn7-8"  
rid="deqn9a-10v"  
rid="deqn11a-12c"

I want a regex to match each deqnX-Y where X and Y are either both integers or both combination of integer and alphabet and if there is a match store X and Y in some variables. I tried using the regex (^(\\d+)-(\\d+)$|^(\\d+[az])-(\\d+[az]))$ , but how do I get the values of the matched groups in variables? For a match between two integers the groups would be (I think)

Groups[2].Value 
Groups[3].Value

and for match between two integer and alphabet combo will be

Groups[4].Value
Groups[5].Value

How do I determine which match actually occured and then capture the matching groups accordingly?

As branch reset (?|) is not supported in C#, we can use named capturing group with same name like

deqn(?:(?<match1>\d+)-(?<match2>\d+)|(?<match1>\d+\w+)-(?<match2>\d+\w+))\b

regextester demo

C# code

String sample = "deqn1-2";
Regex regex = new Regex("deqn(?:(?<match1>\\d+)-(?<match2>\\d+)|(?<match1>\\d+\\w+)-(?<match2>\\d+\\w+))\\b");

Match match = regex.Match(sample);

if (match.Success) {
    Console.WriteLine(match.Groups["match1"].Value);
    Console.WriteLine(match.Groups["match2"].Value);
}

dotnetfiddle demo

You could simply not care . One of the pairs will be empty anyway. So what if you just interpret the result as a combination of both? Just slap them together. First value of the first pair plus first value of the second pair, and second value of the first pair plus second value of the second pair. This always gives the right result.

Regex regex = new Regex("^deqn(?:(\\d+)-(\\d+)|(\\d+[a-z])-(\\d+[a-z]))$");
foreach (String str in listData)
{
    Match match = regex.Match(str);
    if (!match.Success)
        continue;
    String value1 = Groups[1].Value + Groups[3].Value;
    String value2 = Groups[2].Value + Groups[4].Value;
    // process your strings
    // ...
}

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