This is a regex-based solution to introduce thousand separators:
String separateThousands(String s) {
return s.replaceAll(
"(?<=\\G\\d{3})(?=\\d)" + "|" + "(?<=^-?\\d{1,3})(?=(?:\\d{3})+(?!\\d))",
","
);
}
This will transform "-1234567890.1234567890"
to "-1,234,567,890.1234567890"
.
See also
- codingBat separateThousands using regex (and unit testing how-to)
- Explanation of how it works, and alternative regex that also uses
\G
.
This one is more abstract, but you can use \G
and fixed-length lookbehind to split
a long string into fixed-width chunks:
String longline = "abcdefghijklmnopqrstuvwxyz";
for (String line : longline.split("(?<=\\G.{6})")) {
System.out.println(line);
}
/* prints:
abcdef
ghijkl
mnopqr
stuvwx
yz
*/
You don't need regex for this, but I'm sure there are "real life" scenarios of something that is a variation of this technique.