【问题标题】:How to pull double out of string with matcher如何使用匹配器从字符串中拉出双倍
【发布时间】:2015-04-22 04:38:45
【问题描述】:

我正在尝试从字符串中解析出双精度。我有代码:

Pattern p = Pattern.compile("-?\\d+(\\.\\d+)?");
Matcher m = p.matcher("reciproc(2.00000000000)");
System.out.println(Double.parseDouble(m.group())); 

此代码引发 java.lang.IllegalStateException。我希望输出为 2.00000000000。我从Java: Regex for Parsing Positive and Negative Doubles 那里得到了正则表达式,它似乎对他们有用。我也尝试了其他一些正则表达式,它们都抛出了同样的错误。我在这里遗漏了什么吗?

【问题讨论】:

  • 那么你的结果是什么?
  • 它抛出一个 java.lang.IllegalStateException
  • 检查传递给Pattern.matcher()的字符串。你认为它会与你给出的正则表达式匹配吗?
  • Pattern.matches("-?\\d+(\\.\\d+)?", "reciproc(2.00000000000)") 返回错误

标签: java regex matcher


【解决方案1】:

这不是您的正则表达式的问题,而是您如何使用 Matcher 类。您需要先调用 find()。

这应该可行:

    Pattern p = Pattern.compile("-?\\d+(\\.\\d+)?");
    String text = "reciproc(2.00000000000)";
    Matcher m = p.matcher(text);
    if(m.find())
    {
        System.out.println(Double.parseDouble(text.substring(m.start(), m.end())));
    }

或者:

    Pattern p = Pattern.compile("-?\\d+(\\.\\d+)?");
    Matcher m = p.matcher("reciproc(2.00000000000)");
    if(m.find())
    {
        System.out.println(Double.parseDouble(m.group()));
    }

有关详细信息,请参阅the docs

【讨论】:

    【解决方案2】:

    p.matcher("2.000000000000");

    您的模式应与Pattern.compile() 中提供的正则表达式匹配

    有关正则表达式和模式的更多信息:

    https://docs.oracle.com/javase/tutorial/essential/regex/ https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

    【讨论】:

    • 你的答案到底是什么?我需要把它从“reciproc(2.00000000000)”中拉出来
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多