Find/replace number with commas in Java
Two of the really nice things about regular expressions are:


they can be compiled, which makes them fast, and reusable
they can replace what's between characters, not just the characters themselves.


In your case, you can reduce it to a "simple" lookaround regular expression. What you are looking for, is the gap between two digits...

in a regular expression, the gap can have no width. So, look for a place that follows a digit, and is also followed by a digit. Then, replace that place with a separator.

Then, compile and save that expression away, and reuse it:

private static final Pattern BETWEEN_DIGITS = Pattern.compile("(?&lt;=\\d)(?=\\d)");

public static String formatNumber(String text, char separator) {
    return BETWEEN_DIGITS.matcher(text).replaceAll("" + separator);
}


That pattern is complicated.... but read up on look-behinds, and look-aheads: http://www.regular-expressions.info/lookaround.html