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?
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With