Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex matcher doesn't group as expected

Tags:

java

regex

I have a regex

.*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*?

I want to match any string that contains a numerical value followed by "-" and another number. Any string can be in between.

Also, I want to be able to extract the numbers using group function of Java Matcher class.

Pattern pattern = Pattern.compile(".*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*?");
Matcher matcher = pattern.matcher("13.9 mp - 14.9 mp");
matcher.matches();

I expect this result:

matcher.group(1) // this should be 13.9 but it is 13 instead
matcher.group(2) // this should be 14.9 but it is 14 instead

Any idea what I am missing?


1 Answers

Your current pattern has several problems. As others have pointed out, your dots should be escaped with two backslashes if you intend for them to be literal dots. I think the pattern you want to use to match a number which may or may not have a decimal component is this:

(\\d+(?:\\.\\d+)?)

This matches the following:

\\d+          one or more numbers
(?:\\.\\d+)?  followed by a decimal point and one or more numbers
              this entire quantity being optional

Full code:

Pattern pattern = Pattern.compile(".*?(\\d+(?:\\.\\d+)?).*?-.*?(\\d+(?:\\.\\d+)?).*?");
Matcher matcher = pattern.matcher("13.9 mp - 14.9 mp");
while (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

Output:

13.9
14.9
like image 79
Tim Biegeleisen Avatar answered Sep 10 '26 17:09

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!