货币值字符串由逗号分隔

RP-*_*RP- 6 java string-split

我有一个字符串,其中包含格式化的货币值,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个输出是:

45,890 //removing the decimals as the reg ex is exclusive
12,345
23,765
56,908.50
Run Code Online (Sandbox Code Playgroud)

有人可以帮我这个吗?

Boh*_*ian 11

你需要一个正则表达式"后面看" (?<=regex),它匹配,但确实消耗:

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

这是您现在正在使用的测试用例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

45,890.00
12,345.00
23,765.34
56,908.50
Run Code Online (Sandbox Code Playgroud)