我有一个字符串,如下所示:
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/