2016-12-13 7 views
-1

사용자 결정에 따라 런타임에 캡처 그룹과 함께 매우 큰 정규식을 작성하려고한다고 가정합니다.Java regex - 일치하는 캡처 그룹을 확인하고 발생 횟수를 확인합니다.

간단한 예 :

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Test {  
    static boolean findTag, findWordA, findOtherWord, findWordX; 

    static final String TAG = "(<[^>]+>)"; 
    static final String WORD_A = "(wordA)"; 
    static final String OTHER_WORD = "(anotherword)"; 
    static final String WORD_X = "(wordX)"; 

    static int tagCount = 0; 
    static int wordACount = 0; 
    static int otherWordCount = 0; 
    static int wordXCount = 0; 

    public static void main(String[] args) { 
     // Boolean options that will be supplied by the user 
     // make them all true in this example 
     findTag = true; 
     findWordA = true; 
     findOtherWord = true; 
     findWordX = true; 

     String input = "<b>this is an <i>input</i> string that contains wordX, wordX, anotherword and wordA</b>"; 

     StringBuilder regex = new StringBuilder(); 

     if (findTag) 
      regex.append(TAG + "|"); 

     if (findWordA) 
      regex.append(WORD_A + "|"); 

     if (findOtherWord) 
      regex.append(OTHER_WORD + "|"); 

     if (findWordX) 
      regex.append(WORD_X + "|"); 

     if (regex.length() > 0) { 
      regex.setLength(regex.length() - 1); 
      Pattern pattern = Pattern.compile(regex.toString()); 

      System.out.println("\nWHOLE REGEX: " + regex.toString()); 
      System.out.println("\nINPUT STRING: " + input); 

      Matcher matcher = pattern.matcher(input); 

      while (matcher.find()) { 
       // only way I know of to find out which group was matched: 
       if (matcher.group(1) != null) tagCount++; 
       if (matcher.group(2) != null) wordACount++; 
       if (matcher.group(3) != null) otherWordCount++; 
       if (matcher.group(4) != null) wordXCount++; 
      } 

      System.out.println(); 
      System.out.println("Group1 matches: " + tagCount); 
      System.out.println("Group2 matches: " + wordACount); 
      System.out.println("Group3 matches: " + otherWordCount); 
      System.out.println("Group4 matches: " + wordXCount); 

     } else { 
      System.out.println("No regex to build."); 
     } 
    } 
} 

문제는 그 사용자가 검색하고자하는 정규식/그룹을 사전에 알고있는 경우에만 나는 각 그룹의 일치를 계산 할 수 있다는 것입니다.

전체 정규식에 더 많은 캡처 그룹이 포함되며 더 복잡해집니다.

사용자가 찾고자하는 그룹을 미리 모른 채 각 그룹의 출현 횟수를 계산할 수 있도록 일치하는 캡처 그룹을 어떻게 결정할 수 있습니까?

+0

어쩌면 명백한 대답을하지만, 당신이 사용할 수있는 깨닫는다'groupCount()는'그룹의 수를 결정? –

+1

실제로는 관계가 없지만'StringBuilder'는 문자열 연결을 피하기 위해 정확하게 사용됩니다 (각 연결 표현식에 대해 추가로'StringBuilder'를 생성합니다). 그래서'regex.append (TAG + "|");'regex.append (TAG) .append ("|");'를 사용하십시오. – Pshemo

+0

@PatrickParker 그룹 수는 충분하지 않습니다. 그룹 수를 알아야합니다. – AndroidX

답변

0

정규식 named groups를 사용하는 구성 :

(?<tag>wordA)|(?<wordx>wordX)|(?<anotherword>anotherword) 
+0

그것은 .... 호기심에서 우리가 할 수있는 유일한 방법은 무엇입니까? – AndroidX

+0

"패턴"이 아니기 때문에 간단하게 평등 테스트를하기 때문에 여기에도 정규식이 필요하다는 것을 알지 못합니다. – sweaver2112

+0

패턴을 사용합니다 ... 위의 코드는 단순한 예제를위한 것입니다. – AndroidX