【问题标题】:Extracting Scientific Number from String without the spaces in the string in Java从Java中的字符串中提取没有空格的科学数字
【发布时间】:2015-05-14 06:56:58
【问题描述】:

我需要从字符串中提取所有数字。我这样做是为了将科学记数法中的数字转换为十进制形式,保持字符串的其余部分不变。

示例:“距离为 4.62664581051E9”变为“距离为 4626645810.51”

public static void main (String[] args) throws java.lang.Exception
{
        NumberFormat fm1 = new DecimalFormat(",##0.00##");
        String str = "NetMV4.62664581051E9";
        StringBuilder parameterBuilder = new StringBuilder();
        Scanner scanner = new Scanner(str);

        while (scanner.hasNext()) {
            if (scanner.hasNextDouble() && !scanner.hasNextInt()) {
                parameterBuilder.append(fm1.format(scanner.nextDouble()));
            } else {
                parameterBuilder.append(scanner.next() + " ");
            }
        }       
        scanner.close();
        System.out.println(parameterBuilder.toString());
}

到目前为止,我一直在使用 Scanner 类来提取数字。它工作正常,但在“距离=4.62664581051E9”(无空格)等情况下失败

我可以创建一个自定义解析器并解析字符串,但正在寻找更好的案例。

谢谢

【问题讨论】:

  • 不要在分隔符上匹配,对数字本身使用正匹配。所以,不要使用 Scanner,因为它是错误的工具。使用Pattern.compile(...).matcher(input),然后在matcher.find() 上循环。

标签: java regex string java.util.scanner


【解决方案1】:

使用正则表达式怎么样?如果可以,请使用:

[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?

这是here的回答

测试:https://regex101.com/r/bK8iH9/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2017-04-07
    • 2012-07-12
    • 2015-06-19
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多