0

I need a regex to properly parse ranges of two real numbers (unsigned), presented with a hyphen.

Valid inputs:

1-3

3.14-7.50

0-4.01

It's Java on Android.

My current approach:

Pattern pattern = Pattern.compile("(?<Minimum>\\d+(\\.\\d+))-(?<Maximum>\\d+(\\.\\d+))");
Matcher matcher = pattern.matcher("3.14-5.2");
String min = matcher.group("Minimum");
String max = matcher.group("Maximum");

It crashes on attempting to retrieve the minimum.

java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.getMatchedGroupIndex(Matcher.java:1314)
    at java.util.regex.Matcher.group(Matcher.java:572)

I can't really see what's wrong with the expression.

I would particularly appreciate an explanation on what the problem with it is. A regex allowing for optional white space around the hyphen would be extra nice, too (I'd like it to work that way but I dropped this for now as I can't get it to work at all).

Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91

1 Answers1

1

You need to make decimal part optional:

Pattern pattern = Pattern.compile(
   "(?<Minimum>\\d+(?:\\.\\d+)?)-(?<Maximum>\\d+(?:\\.\\d+)?)");
  • ? after (?:\\.\\d+) will make that group an optional match
  • Better to use ?: for making it a non-capturing group

Also you need to call matcher.find() or matcher.matches() before calling .group(int) method.

anubhava
  • 761,203
  • 64
  • 569
  • 643