Alex Alex - 2 months ago 6
Java Question

Regex: pattern for simple division string

I have a string that follows this pattern:

2/9 (22%)


where the
2
or the
9
could contain 1 or more digits. I need to parse out those two integers, so I came up with this pattern:

String patternString = "([0-9]+)/([0-9]+).*";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(stat);

if (matcher.matches()) {
int i = Integer.parseInt(matcher.group(0));
int j = Integer.parseInt(matcher.group(2));
}


But this crashes with the following error:

java.lang.NumberFormatException: Invalid int: "2/9 (22%)"


which means that it is matching the entire string on the 0th group.

I've also tried placing the
/
character inside of
[/]
, but same result.

What am I doing wrong? Thanks!

Answer

You should be using group(1) and group(2).

group(0) is the entire string, which you actually stated in the question