2012-07-22 53 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

我想要得到的是:

group(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