3

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
  • 1
    Escape the dots in \d+.*\d* or better, use \d+(?:\.\d+)? Commented Apr 14, 2017 at 8:05

2 Answers 2

2

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

Comments

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

. between '\d+' and '\d' in your regex should be changed to \.

2 Comments

This would match a sentence ending in a number. Have a look here.
the regex is Jones's ,I just modify it to matche value he want .Maybe that is he want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.