Return 单个正则表达式匹配的命名捕获组名称和值
Return a single regex match's Named Capture Group name and value
我有这个 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");
}
}
我想打印出捕获组的名称以及匹配列表中的值,这可以吗?
例如,当我输入 "var++" 时,它应该输出:
Char : v
Char : a
Char : r
Plus : +
Plus : +
您可以使用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;
}
}
}
}
我有这个 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");
}
}
我想打印出捕获组的名称以及匹配列表中的值,这可以吗?
例如,当我输入 "var++" 时,它应该输出:
Char : v
Char : a
Char : r
Plus : +
Plus : +
您可以使用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;
}
}
}
}