简体   繁体   English

返回单个正则表达式匹配的命名捕获组名称和值

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

I have this Tokinizer Class that breaks up a string input:我有这个分解字符串输入的 Tokinizer Class:

    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:例如,当我输入“var++”时,它应该是 output:

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

You can use Regex.GroupNameFromNumber您可以使用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;
            }
        } 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM