java - 使用 String.replace ("",""替换以逗号分隔的数字;

标签 java regex

我有一个字符串,如下所示:

13,000,000 岁了

现在我想将数字转换为英文单词,我已经准备好一个函数,但是我发现在这种情况下检测原始数字 (13,000,000) 存在问题,因为它用逗号分隔。

目前我正在使用以下正则表达式来检测字符串中的数字:

stats = stats.replace((".*\\d.*"), (NumberToWords.start(Integer.valueOf(notification_data_greet))));

但是上面的好像不行,有什么建议吗?

最佳答案

您需要使用允许逗号的 RegEx 提取数字。我现在能想到的最强大的是

\d{1,3}(,?\d{3})*

Wich 匹配任何带正确放置的逗号和不带逗号的无符号整数(以及它们的奇怪组合,如 100,000000)
然后将匹配项中的所有 , 替换为空字符串,您就可以照常解析了:

Pattern p = Pattern.compile("\\d{1,3}(,?\\d{3})*"); // You can store this as static final
Matcher m = p.matcher(input);
while (m.find()) { // Go through all matches
    String num = m.group().replace(",", "");
    int n = Integer.parseInt(num);
    // Do stuff with the number n
}

工作示例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        String input = "1,300,000,000";
        Pattern p = Pattern.compile("\\d{1,3}(,?\\d{3})*"); // You can store this as static final
        Matcher m = p.matcher(input);
        while (m.find()) { // Go through all matches
            String num = m.group().replace(",", "");
            System.out.println(num);
            int n = Integer.parseInt(num);
            System.out.println(n);
        }
    }
}

给出输出

1300000000
1300000000

关于java - 使用 String.replace ("",""替换以逗号分隔的数字;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24908793/

相关文章:

c# - 反序列化对象的好模式是什么?

用于生成 C++ 源代码的 Java 库

java - 创建用户定义的异常类-获取 null 作为答案(JAVA)

java - 将 Floyd-Warshall 限制为路径长度 k

regex - 正则表达式: match x times OR y times

python - Python 中的 RE - lastindex 属性

regex - Java正则表达式除最后一个字符外的所有字符

java - 在 J2ME 中如何从另一个类对象中获取一个 byte[] 对象?

正则表达式:匹配多个模式并获得字符串中间

javascript - mongodb正则表达式参数