Java – comma separated string of currency values
•
Java
I have a string that contains formatted currency values, such as 45890.00 and multiple values separated by commas, 890.00,12345.00,23765.34,56908.50
I want to extract and process all monetary values, but I can't find the correct regular expression. That's what I'm trying to do
public static void main(String[] args) { String currencyValues = "45,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); } }
This output is:
45,890 //removing the decimals as the reg ex is exclusive 12,345 23,765 56,908.50
Can someone help me with this?
Solution
You need a regular expression "look behind" (? < = regex), which matches, but consumes:
String regEx = "(?<=\\.[0-9]{2}),";
This is the test case you are using now:
public static void main(String[] args) { String currencyValues = "45,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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码