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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.