【问题标题】:Java regex matcher doesn't group as expectedJava 正则表达式匹配器未按预期分组
【发布时间】:2017-09-10 11:34:40
【问题描述】:

我有一个正则表达式

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

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

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

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+(?:\.\d+)?

标签: java regex matcher


【解决方案1】:

您当前的模式有几个问题。正如其他人指出的那样,如果您打算将点作为文字点,则应使用两个反斜杠对其进行转义。我认为你想用来匹配可能有或没有小数部分的数字的模式是这样的:

(\\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

【讨论】:

    【解决方案2】:
    .*?(\d+\.*\d*).*?-.*?(\d+\.*\d*).*?
    

    。正则表达式中的 '\d+' 和 '\d' 之间应更改为 \.

    【讨论】:

    • 这将匹配以数字结尾的句子。看看here
    • 正则表达式是琼斯的,我只是修改它以匹配他想要的值。也许这就是他想要的。
    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2016-11-23
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多