Alex Alex - 1 year ago 68
Java Question

Regex: pattern for simple division string

I have a string that follows this pattern:

2/9 (22%)

where the
or the
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(;
int j = Integer.parseInt(;

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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download