Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式匹配器不';t组如预期_Java_Regex_Matcher - Fatal编程技术网

Java正则表达式匹配器不';t组如预期

Java正则表达式匹配器不';t组如预期,java,regex,matcher,Java,Regex,Matcher,我有一个正则表达式 .*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*? 我想匹配任何包含一个数值后跟“-”和另一个数字的字符串。任何字符串都可以介于两者之间 另外,我希望能够使用Java Matcher类的group函数提取数字 Pattern pattern = Pattern.compile(".*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*?"); Matcher matcher = pattern.matcher("13.9 mp

我有一个正则表达式

.*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*?
我想匹配任何包含一个数值后跟“-”和另一个数字的字符串。任何字符串都可以介于两者之间

另外,我希望能够使用Java Matcher类的group函数提取数字

Pattern pattern = Pattern.compile(".*?(\\d+.*?\\d*).*?-.*?(\\d+.*?\\d*).*?");
Matcher matcher = pattern.matcher("13.9 mp - 14.9 mp");
matcher.matches();
我期望这一结果:

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

你知道我遗漏了什么吗?

你当前的模式有几个问题。正如其他人所指出的,如果你想让点成为文字点,那么应该用两个反斜杠转义。我认为您想要用来匹配可能有或可能没有十进制成分的数字的模式是:

(\\d+(?:\\.\\d+)?)
这与以下内容相匹配:

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

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));
}
输出:

13.9
14.9

。正则表达式中的“\d+”和“\d”之间应改为\。

\d+.\d*
中转义点,或者更好,使用
\d+(?:\。\d+)
这将匹配以数字结尾的句子。看看。正则表达式是琼斯的,我只是修改它以匹配他想要的值。也许这就是他想要的。
.*?(\d+\.*\d*).*?-.*?(\d+\.*\d*).*?