I want to get out numbers from a line with pattern, but it wont group numbers as I would like.
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));
}
}
Output:
group(1) = text:
group(2) = 7
group(3) = 7
What I want to get is:
group(2) = 1
group(3) = 2
…
group(8) = 7
Can I get this from this one pattern or should I make another one ?
You cannot. Groups always correspond to capturing groups in the regular expression. That is, if you have one capturing group, there cannot be more than one group in the match. It is irrelevant how often a portion (even a capturing group) is repeated during the match. The expression itself defines how many groups the final match can have.