Comma Separated Currency Values

I have a String that contains formatted currency values, such as 45,890.00several values ​​separated by commas, like 45,890.00,12,345.00,23,765.34,56,908.50..

I want to extract and process all currency values, but could not find the correct regular expression for this. This is what I tried

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);
    }
}

The result of this:

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

Can someone please help me with this?

+6
source share
3 answers

You need a regex "look behind" (?<=regex)that matches but consumes:

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

Here is your test case:

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);
    }
}

Conclusion:

45,890.00
12,345.00
23,765.34
56,908.50
+11
source

, ( , ):

 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());
 }

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

:

  • \\d
  • \\d{1,3} 1-3
  • (\\d{1,3},)? 1-3 , .
  • \\.
  • \\d{2} 2 .

, , , , , .

EDIT:

@tobias_k: \\d{1,3}(,\\d{3})*\\.\\d{2} , :

  • 1,000,000,000.00

:

  • 1,00.00
+4

, . , :

String str = "1 123,67 , 34 234 000 , 1234 ";

Not all values ​​are decimal here. There must be a way to decide if the currency is decimal or integer.

0
source

All Articles