-1

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
nicael
  • 18,550
  • 13
  • 57
  • 90
sinclair
  • 2,812
  • 4
  • 24
  • 53

1 Answers1

3

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
Dici
  • 25,226
  • 7
  • 41
  • 82
  • @Tunaki in addition to your way you can precompile a Pattern, and use that Pattern to perform the same function to speed up the proces (if it should be performance friendly) – n247s Jul 24 '16 at 17:09
  • @n247s `String.replaceAll` does not directly support passing a `Pattern`. How would you use your pattern in that case ? Plus, I think building the new string is th part that is actually the most expensive for such a simple regex. But in a more general context, you're right – Dici Jul 24 '16 at 17:11
  • Doesn't regex object have a replaceall method? –  Jul 24 '16 at 17:52
  • @sln what do you call a regex object ? I looked at the doc of `Pattern` and this class does not have such method – Dici Jul 24 '16 at 18:23
  • @Dici The way to use a Pattern is not to pass it in a String method (as this is obviously not possible) but use it as this instead: `patternInstance.matcher("abc123").replaceAll("$1$1$1");`. The thing is that `String.replaceAll()` is calling this method as well, but instead is compiling a new Pattern for each call (relative expensive) while you can reuse the same pattern for every replacement. And therefore save a bit of performance. And in addition you can hold onto the Matcher instance as well, although the creation of a Matcher instance isn't that performance consuming as compiling a Patter – n247s Jul 24 '16 at 20:01