简体   繁体   中英

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 : +

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;
            }
        } 
    }
}

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