Search code examples
c#regexnamed-captures

Return a single regex match's Named Capture Group name and value


I have this Tokinizer Class that breaks up a string input:

    public class Tokinizer
    {
        public static Regex r = new Regex(
            "(?<Equals>=)" +
            "|(?<Plus>\\+)" +
            "|(?<Minus>\\-)" +
            "|(?<Divide>\\/)" +
            "|(?<Multiply>\\*)" +
            "|(?<Exclamation>\\!)" +
            "|(?<GreaterThan>\\>)" +
            "|(?<SmallerThan>\\<)" +
            "|(?<OpenParenthesis>\\()" +
            "|(?<CloseParenthesis>\\))" +
            "|(?<OpenBracket>\\[)" +
            "|(?<CloseBracket>\\])" +
            "|(?<OpenBrace>\\{)" +
            "|(?<CloseBrace>\\})" +
            "|(?<Colon>\\:)" +
            "|(?<SemiColon>\\;)" +
            "|(?<Comma>\\,)" +
            "|(?<FullStop>\\.)" +
            "|(?<Quatation>\\\")" +
            "|(?<Char>[a-zA-Z0-9])" +
            "|(?<space>\\s+)", RegexOptions.ExplicitCapture);

        public static void GetTokens(string input)
        {            
            foreach (var t in r.Matches(input))
            {
                Console.WriteLine("Named Group : Token Value");
            }            
        }

I want to print out the the name of the capture group aswell as the value from a list of matches, is this possible to do?

For example when I give the input "var++" it should output:

Char : v
Char : a
Char : r
Plus : +
Plus : +

Solution

  • You can use Regex.GroupNameFromNumber

    public static void GetTokens(string input)
    {
        foreach (Match match in r.Matches(input))
        {
            for (int i = 1; i < match.Groups.Count; i++)
            {
                var group = match.Groups[i];
                if (group.Success){
                    Console.WriteLine("{0} : {1}", r.GroupNameFromNumber(i), match);
                    break;
                }
            } 
        }
    }