Click here to Skip to main content
15,389,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have this
// ... Input string.
            string input = "Left12345Right";

            // ... Use named group in regular expression.
            Regex expression = new Regex(@"Left(?<middle>\d+)Right");

            // ... See if we matched.
            Match match = expression.Match(input);
            if (match.Success)
            {
                // ... Get group by name.
                string result = match.Groups["middle"].Value;
                Console.WriteLine("Middle: {0}", result);
                Console.WriteLine(match.Name);
            }
            // Done.
            Console.ReadLine();

As I read the info, .Name should return the name of the capturing group, but for me it only returns 0, and I can't understand why.

So I hope that some here can tel me what I'm doing wrong. (I'm new to C# and regex).

Cheers
/LR

What I have tried:

Googled to find answer, but found nothing.
Posted
Updated 4-Feb-20 6:46am
Comments
Richard MacCutchan 4-Feb-20 12:36pm
   
According to my tests, and the documentation, Match does not contain a Name property.
Richard MacCutchan 4-Feb-20 12:53pm
   
The compiler rejected it when I tried. I Must take a longer look at that.

Try this:
C#
Console.WriteLine(match.Groups[1].Name);
The first group in a Match is the whole match, which consists of all the Groups in the Match.
   
Comments
Maciej Los 4-Feb-20 14:24pm
   
5ed!
Lupu5R3x 5-Feb-20 11:43am
   
Hi I tried that, but [1] just give me the name of the first group name in my pattern, not the name of the captured group.

eg. if I have this pattern (?(abc)|(?<d>def)|(?<g>ghi) and test string def [1] just gives me a :(

/LR
The Match instance itself is equivalent to the first object in the collection, at Match.Groups[0], which represents the entire match.

There is no sensible name that could be given to the group representing the entire match, so it gets the name 0 by default. This allows you to reference the entire match in a replacement expression by using $0.

It's not clear from your question what you're trying to achieve with the Name property. Were you looking for the GetGroupNames method[^] instead?
   
Comments
Maciej Los 4-Feb-20 14:24pm
   
5ed!
Lupu5R3x 5-Feb-20 11:23am
   
I'm trying to convert a Autoit regex pattern like this "(abc)|(def)|(ghi)", 1
Where ,1 returns a match of arrays.

So the result of "def" would return [0] = , [1] = def

But sins I couldn't find any equitant to match of arrays in C#, my hope was that I could use naming groups to return the name of the group that was matched.

eg. (?abc)|(?<d>def)|(?<g>ghi) and test def should (was my thought) return d.

But when trying what @OriginalGriff sugested, I just get the group name I specified so [1] returns a, [2] = b but that it does regardless of what the match is.

And yes I should have specified exactly what I was trying to achieve, with the regex, sry for that :(

/LR
Richard Deeming 5-Feb-20 11:46am
   
I'm not familiar with the "match of arrays" feature, but named groups seems like the way to go:
Regex expression = new Regex(@"(?<a>abc)|(?<b>def)|(?<c>ghi)", RegexOptions.ExplicitCapture);
Match match = expression.Match(input);
if (match.Success)
{
    if (match.Groups["a"].Success)
    {
        // Matched first option...
    }
    else if (match.Groups["b"].Success)
    {
        // Matched second option...
    }
    else if (match.Groups["c"].Success)
    {
        // Matched third option...
    }
}
Lupu5R3x 5-Feb-20 12:17pm
   
Hmm, yes it seems that it would be the most simple solution to my problem. :)

Regardless of how annoying it is that all my one line regex's end up as several lines in C# to get the same result :( the last regex I translated went from one line to 10 lines in C# :O course C# don't support \K :'(

/LR
Richard Deeming 5-Feb-20 12:34pm
   
I'm not familiar with \K - is it some sort of look-behind operator?

Grouping Constructs in Regular Expressions | Microsoft Docs[^]

string input = "2010 1999 1861 2140 2009";
string pattern = @"(?<=\b20)\d{2}\b";
foreach (Match match in Regex.Matches(input, pattern))
{
    Console.WriteLine(match.Value);
}

/*
Output:
10
09
*/
Lupu5R3x 5-Feb-20 12:47pm
   
\K "Resets start of match at the current point in subject string. Note that groups already captured are left alone and still populate the returned array; it is therefore always possible to backreference to them later on. Action of \K is similar but not identical to a look-behind, in that \K can work on alternations of varying lengths."

So this regreplace".{1,60}\K(\s{1,2}|$)", "\r\n"
which returned one string "splitted" by 60 char in one string at once, ended up as this.
string splitPattern = @"(.{1,60})(\s{1,2}|$)";
RegexOptions regexOptions = RegexOptions.IgnoreCase;
Regex splitText = new Regex(splitPattern, regexOptions);
StringBuilder result = new StringBuilder();

foreach (Match match in splitText.Matches(input))
{
if (match.Success)
{
result.Append(match.Groups[0].Value + "\r\n");
}
}
return result.ToString();

/LR

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900