BJ Dela Cruz
BJ Dela Cruz

Reputation: 5354

Capturing groups in Java regex

I wrote this regex:

String REGEX = "^\\s+something\\s+(not\\s+)?else\\s+((\\d+|\\d+-\\d+),\\s+)*(\\d+|\\d+-\\d+)$";

Here is my main method:

  public static void main(String... args) {
    Matcher matcher = PATTERN.matcher(" something else 1, 3, 4, 5-7");
    if (matcher.matches()) {
      for (int index = 0; index <= matcher.groupCount(); index++) {
        System.out.println(index + ": " + matcher.group(index));
      }
    }
  }

and here is my output:

0:  match cos 1, 3, 4, 5-7
1: null
2: 4, 
3: 4
4: 5-7

It seems like 1 and 3 are not being captured. (The outputs 4 and 5-7 are fine.) How can I fix my regex so that I can capture them (and capture them without a comma at the end)?

Upvotes: 1

Views: 1840

Answers (1)

Pshemo
Pshemo

Reputation: 124215

If your goal is to find numbers that are predicted by something else or something not else then maybe group them in one group, and then split with ,\\s+, for example

String REGEX = "^\\s+something\\s+(not\\s+)?else\\s+((((\\d+|\\d+-\\d+),\\s+)*)(\\d+|\\d+-\\d+))$";
Pattern PATTERN = Pattern.compile(REGEX);
Matcher matcher = PATTERN.matcher(" something else 1, 3, 4, 5-7");
if (matcher.matches()) {
    System.out
            .println(Arrays.toString(matcher.group(2).split(",\\s+")));
}

output:

[1, 3, 4, 5-7]

Upvotes: 2

Related Questions