2009-07-22 2 views
8

나는 .NET Regex와 유사합니다 :정규식 : 그룹 이름을 얻는 방법

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

을 사용하고 있습니다. "AAABBBAAA", 그 다음 반복을 반복합니다.

내 목표는 정규식 일치 그룹을 사용하여 일치 유형을 찾는 것입니다. 따라서이 정규식은 다음과 같습니다.

  • Type1
  • Type2
  • Type1
  • I cann 어떤 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)); 
          }  
         }