我有一个字符串,其中包含格式化的货币值,如45,890.00和多个值由逗号分隔,890.00,12,345.00,23,765.34,56,908.50 ..
我想提取并处理所有货币值,但无法找出正确的正则表达式,这就是我所尝试的@H_404_3@
- public static void main(String[] args) {
- String currencyValues = "45,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
有人可以帮我这个吗?@H_404_3@
解决方法
你需要一个正则表达式“后面看”(?< = regex),它匹配,但消耗:
- String regEx = "(?<=\\.[0-9]{2}),";
这是您现在正在使用的测试用例:@H_404_3@
- public static void main(String[] args) {
- String currencyValues = "45,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