This question is a combination of regular expression practice and unit testing practice.
Regular Expression Part
I created this problem separateThousandsfor personal practice:
Given a number as a string, enter commas to separate thousands. The number may contain an optional minus sign and an optional decimal part. There will be no extra leading zeros.
Here is my solution:
String separateThousands(String s) {
return s.replaceAll(
String.format("(?:%s)|(?:%s)",
"(?<=\\G\\d{3})(?=\\d)",
"(?<=^-?\\d{1,3})(?=(?:\\d{3})+(?!\\d))"
),
","
);
}
How it works, it classifies two types of commas: the first and the rest. In the above regular expression, the rest of the subpattern actually appears before the first. The match will always be the zero length that will be replaceAllwith ",".
, , , 3 , , , . , .
^, 1 3 . , ( $ \.).
:
, author , . :
INPUT, OUTPUT
"1000", "1,000"
"-12345", "-12,345"
"-1234567890.1234567890", "-1,234,567,890.1234567890"
"123.456", "123.456"
".666666", ".666666"
"0", "0"
"123456789", "123,456,789"
"1234.5678", "1,234.5678"
"-55555.55555", "-55,555.55555"
"0.123456789", "0.123456789"
"123456.789", "123,456.789"
, , , , - .. ( , , ).