2012-07-22 5 views
0

패턴이있는 줄에서 숫자를 가져오고 싶지만 원하는대로 그룹 번호가 없습니다.정확히 n 번 - 그룹

public static void main(String[] args) { 
    Pattern pattern = Pattern.compile("(.*?)((\\d+),{0,1}\\s*){7}"); 
    Scanner in = new Scanner("text: 1, 2, 3, 4, 5, 6, 7"); // new Scanner(new File("data.txt")); 
    in.useDelimiter("\n"); 

    try { 
     while(!(in.hasNext(pattern))) { 
      //Skip corrupted data 
      in.nextLine(); 
     } 
    } catch(NoSuchElementException ex) { 
    } 
    String line = in.next(); 
    Matcher m = pattern.matcher(line); 
    m.matches(); 
    int groupCount = m.groupCount(); 
    for(int i = 1; i <= groupCount; i++) { 
     System.out.println("group(" + i + ") = " + m.group(i)); 
    } 
} 

출력 :

그룹 (1) = 텍스트 :

그룹 (2) = 7

그룹 (3) = 7

내가하고 싶지는 :

그룹 (2) = 1

그룹 (3) = 2

...

그룹 (8) = 7

내가이 하나 개의 패턴에서이받을 수 아니면 다른 일을해야합니까?

답변

0

수 없습니다. 그룹은 항상 정규식의 캡처 그룹에 해당합니다. 즉, 캡처 그룹이 하나 인 경우 일치하는 그룹이 두 개 이상일 수 없습니다. 매치 중에 얼마나 자주 (캡쳐 그룹조차도) 반복되는지는 무의미합니다. 표현 자체는 최종 일치가 가질 수있는 그룹 수를 정의합니다.

1

단순히 정수를 수집하려는 경우 다음 스타일의 패턴을 사용하여 Matcher.find() 메소드를 사용하여 부분 문자열을 반복 할 수 있습니다. 1) 선택적 구분 기호 또는 새 줄. 2) 공백 문자로 둘러싸인 정수 구체적인 캡처 그룹 만 참조 할 수 있기 때문에 그룹 인덱스를 전혀 관리 할 필요가 없습니다. 다음 솔루션은 정규 표현식을 제외하고 아무것도 필요하지 않습니다와 문자의 순서를 통해 단지 반복 정수 찾을 :

package stackoverflow; 

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

import static java.lang.System.out; 
import static java.util.regex.Pattern.compile; 

public final class Q11599271 { 

    private Q11599271() { 
    } 

    // 
    // (2) Let's capture an integer number only  -------------------+ 
    // (1) Let's assume it can start with a new  ------+   | 
    //  line or a comma character      |   | 
    //            +-----+-----+ +-+--+ 
    //            |   | | | 
    private static final Pattern pattern = compile("(?:^\\S+:|,)?\\s*(\\d+)\\s*"); 

    private static Iterable<String> getOut(CharSequence s) { 
     final Collection<String> numbers = new ArrayList<String>(); 
     final Matcher matcher = pattern.matcher(s); 
     while (matcher.find()) { 
      numbers.add(matcher.group(1)); 
     } 
     return numbers; 
    } 

    private static void display(Iterable<String> strings) { 
     for (final String s : strings) { 
      out.print(" "); 
      out.print(s); 
     } 
     out.println(); 
    } 

    public static void main(String[] args) { 
     display(getOut("text: 1, 2, 3, 4, 5, 6, 7")); 
     display(getOut("1, 2, 3, 4, 5, 6, 7")); 
     display(getOut("text: 1, 22, 333 , 4444 , 55555 , 666666, 7777777")); 
    } 

} 

다음 생성합니다 :

1 2 3 4 5 6 7 
1 2 3 4 5 6 7 
1 22 333 4444 55555 666666 7777777 
관련 문제