Currency values string split by comma

前端 未结 3 1566
情书的邮戳
情书的邮戳 2021-01-18 11:57

I have a String which contains formatted currency values like 45,890.00 and multiple values seperated by comma like 45,890.00,12,345.00,23,765.34,56,908.5

3条回答
  •  醉话见心
    2021-01-18 12:31

    You could also use a different regular expression to match the pattern that you're searching for (then it doesn't really matter what the separator is):

     String currencyValues = "45,890.00,12,345.00,23,765.34,56,908.50,55.00,345,432.00";
     Pattern pattern = Pattern.compile("(\\d{1,3},)?\\d{1,3}\\.\\d{2}");
     Matcher m = pattern.matcher(currencyValues);
     while (m.find()) {
        System.out.println(m.group());
     }
    

    prints

    45,890.00
    12,345.00
    23,765.34
    56,908.50
    55.00
    345,432.00
    

    Explanation of the regex:

    • \\d matches a digit
    • \\d{1,3} matches 1-3 digits
    • (\\d{1,3},)? optionally matches 1-3 digits followed by a comma.
    • \\. matches a dot
    • \\d{2} matches 2 digits.

    However, I would also say that having comma as a separator is probably not the best design and would probably lead to confusion.

    EDIT:

    As @tobias_k points out: \\d{1,3}(,\\d{3})*\\.\\d{2} would be a better regex, as it would correctly match:

    • 1,000,000,000.00

    and it won't incorrectly match:

    • 1,00.00

提交回复
热议问题