2009-07-22 6 views
8

私は.NET Regexのように見える:正規表現:グループ名を取得する方法

(?<Type1>AAA)|(?<Type2>BBB) 

私はを使用しています。 "AAABBBAAA"を計算し、マッチを反復処理します。

  • Type1の
  • Type2の
  • Type1の

私はcouldn:これはそれがされるの正規表現用のよう

私の目標は、正規表現一致グループを使用して、マッチタイプを見つけることです任意のGetGroupNameメソッドを見つけることはできません。助けてください。

答えて

7

特定のグループ名を取得する場合は、Regex.GroupNameFromNumberメソッドを使用できます。

//regular expression with a named group 
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled); 

//evaluate results of Regex and for each match 
foreach (Match m in regex.Matches("AAABBBAAA")) 
{ 
    //loop through all the groups in current match 
    for(int x = 1; x < m.Groups.Count; x ++) 
    { 
     //print the names wherever there is a succesful match 
     if(m.Group[x].Success) 
      Console.WriteLine(regex.GroupNameFromNumber(x)); 
    } 
} 

また、GroupCollection上の文字列インデクサーがあります。 Match.Groupsプロパティでアクセス可能なオブジェクトであれば、インデックスではなく名前で一致するグループにアクセスできます。

//regular expression with a named group 
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled); 

//evaluate results of Regex and for each match 
foreach (Match m in regex.Matches("AAABBBAAA")) 
{ 
    //print the value of the named group 
    if(m.Groups["Type1"].Success) 
     Console.WriteLine(m.Groups["Type1"].Value); 
    if(m.Groups["Type2"].Success) 
     Console.WriteLine(m.Groups["Type2"].Value); 
} 
17

これはあなたが探しているものですか? Regex.GroupNameFromNumberを使用するので、正規表現の外でグループ名を知る必要はありません。

using System; 
using System.Text.RegularExpressions; 

class Test 
{ 
    static void Main() 
    { 
     Regex regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)"); 
     foreach (Match match in regex.Matches("AAABBBAAA")) 
     { 
      Console.WriteLine("Next match:"); 
      GroupCollection collection = match.Groups; 
      // Note that group 0 is always the whole match 
      for (int i = 1; i < collection.Count; i++) 
      { 
       Group group = collection[i]; 
       string name = regex.GroupNameFromNumber(i); 
       Console.WriteLine("{0}: {1} {2}", name, 
            group.Success, group.Value); 
      } 
     } 
    } 
} 
0

これを試してみてください:

 var regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)"); 
     var input = "AAABBBAAA"; 
     foreach (Match match in regex.Matches(input)) 
     { 
      Console.Write(match.Value); 
      Console.Write(": "); 
      for (int i = 1; i < match.Groups.Count; i++) 
      { 
       var group = match.Groups[i]; 
       if (group.Success) 
        Console.WriteLine(regex.GroupNameFromNumber(i)); 
      }  
     } 
関連する問題