Java regex matcher没有按照预期进行分组

时间:2022-05-02 21:46:08

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.

此外,我还希望能够使用Java Matcher类的组函数提取数据。

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?

知道我错过了什么吗?

2 个解决方案

#1


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

#2


0  

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

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

。在regex中,“\d+”和“\d”之间应该更改为\。

#1


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

#2


0  

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

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

。在regex中,“\d+”和“\d”之间应该更改为\。