Currency values string split by comma
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
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