gpt4 book ai didi

java - 以逗号分隔的货币值字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:33 24 4
gpt4 key购买 nike

我有一个字符串,其中包含格式化的货币值,如 45,890.00 和多个用逗号分隔的值,如 45,890.00,12,345.00,23,765.34,56,908.50 ..

我想提取和处理所有的货币值,但找不到正确的正则表达式,这是我试过的

public static void main(String[] args) {
String currencyValues = "45,890.00,12,345.00,23,765.34,56,908.50";
String regEx = "\\.[0-9]{2}[,]";
String[] results = currencyValues.split(regEx);
//System.out.println(Arrays.toString(results));
for(String res : results) {
System.out.println(res);
}
}

这个的输出是:

45,890 //removing the decimals as the reg ex is exclusive
12,345
23,765
56,908.50

有人可以帮我解决这个问题吗?

最佳答案

您需要一个正则表达式“向后看”(?<=regex) ,它匹配,但确实消耗:

String regEx = "(?<=\\.[0-9]{2}),";

这是您现在可以运行的测试用例:

public static void main(String[] args) {
String currencyValues = "45,890.00,12,345.00,23,765.34,56,908.50";
String regEx = "(?<=\\.[0-9]{2}),"; // Using the regex with the look-behind
String[] results = currencyValues.split(regEx);
for (String res : results) {
System.out.println(res);
}
}

输出:

45,890.00
12,345.00
23,765.34
56,908.50

关于java - 以逗号分隔的货币值字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12401547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com