sinclair sinclair - 4 months ago 8
Java Question

Triplicate all digits in a string

I have a string containing digits like

"abc123"
and I want every digit to show up 3 times like this:
"abc111222333"
.

Is there a way to do this with
replaceAll("\\d+.*", ???)
whereas the
?
is whatever digit was found?

Respectively, is there anything "better" than this?:

String input = "abc1x23z";
String output = input;

for (int i = 0, j = i; i < input.length(); i++) {
char c = input.charAt(i);

if ( Character.isDigit( c ) ) {
String a = output.substring(0, j+1);
String b = output.substring(j, output.length());

output = a + c + b;
j += 3;
}else{
j++;
}
}

System.out.println(output); // abc111x222333z

Answer

You can use "abc123".replaceAll("(\\d)", "$1$1$1")

Explanation:

  • \\d matches a single digit
  • () captures a group
  • $1 points to the first group captured by each match of the regex
Comments