Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency values string split by comma

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.50 ..

I want to extract and process all the currency values, but could not figure out the correct regular expression for this, This is what I have 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 output of this is:

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

Could someone please help me with this one?

like image 271
RP- Avatar asked Sep 13 '12 07:09

RP-


People also ask

How do you separate a string split by a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you convert a number to a comma separated string?

To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas.

How can I parse a string with a comma thousand separator to a number?

We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. We call replace with /,/g to match all commas and replace them all with empty strings.


1 Answers

You need a regex "look behind" (?<=regex), which matches, but does consume:

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

Here's your test case now working:

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

Output:

45,890.00
12,345.00
23,765.34
56,908.50
like image 176
Bohemian Avatar answered Sep 29 '22 14:09

Bohemian