1

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)?

1 Answer 1

2

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] 
Sign up to request clarification or add additional context in comments.

1 Comment

For the record, the ((\\d+|\\d+-\\d+),\\s+)* part matches "1, " on the first repeat, "3, " on the second repeat, then "4, " on the third and final repeat.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.