繁体   English   中英

使用String.replace(“”,“”);替换以逗号分隔的数字;

[英]Replacing digits separated with commas using String.replace(“”,“”);

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

年满13,000,000岁

现在,我想将数字转换为英文单词,我已经准备好一个功能,但是在这种情况下,由于用逗号分隔,因此发现检测原始数字(13,000,000)时遇到了问题。

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

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

但是以上似乎不起作用,有什么建议吗?

尝试使用以下正则表达式来匹配逗号分隔的数字,

\d{1,3}(,\d{3})+

将最后一部分设为可选,以匹配不以逗号分隔的数字,

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

试试这个正则表达式:

[0-9][0-9]?[0-9]?([0-9][0-9][0-9](,)?)*

这匹配每1000个数字之间用逗号分隔的数字。因此它将匹配

10,000,000

但不是

10,1,1,1

您可以借助DecimalFormat而不是正则表达式来完成此操作

    DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance();
    System.out.println(format.parse("10,000,000"));

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

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

Wich会使用正确放置的逗号和不使用逗号(及其奇怪的组合,例如100,000000)来匹配任何未签名的Integer
然后全部更换,由空字符串从比赛和您可以分析像往常一样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM