0

Is it possible to replace digits in a String with that amount of a certain character like 'X' using a regex? (I.e. replace "test3something8" with "testXXXsomethingXXXXXXXX")?

I know I could use a for-loop, but I'm looking for an as short-as-possible (regex) one-liner solution (regarding a code-golf challenge - and yes, I am aware of the codegolf-SE, but this is a general Java question instead of a codegolf question).

  • I know how to replace digits with one character:
    String str = "test3something8".replaceAll("[1-9]", "X"); -> str = "testXsomethingX"
  • I know how to use groups, in case you want to use the match, or add something after every match instead of replacing it:
    String str = "test3something8".replaceAll("([1-9])", "$1X"); -> str = "test3Xsomething8X"
  • I know how to create n amount of a certain character:
    int n = 5; String str = new String(new char[n]).replace('\0', 'X'); -> str = "XXXXX"
  • Or like this:
    int n = 5; String str = String.format("%1$"+n+"s", "").replace(' ', 'X'); -> str = "XXXXX";

What I want is something like this (the code below obviously doesn't work, but it should give an idea of what I somehow want to achieve - preferably even a lot shorter):

String str = "test3Xsomething8X"
  .replaceAll("([1-9])", new String(new char[new Integer("$1")]).replace('\0', 'X')));
// Result I want it to have: str = "testXXXsomethingXXXXXXXX"

As I said, this above doesn't work because "$1" should be used directly, so now it's giving a

java.lang.NumberFormatException: For input string: "$1"


TL;DR: Does anyone know a one-liner to replace a digit in a String with that amount of a certain character?

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • 1
    My personal hint: not everything needs to be solved with regular expressions. One indication that you dont go for regexes: when you need other people to build them. The point is: it will be your code, so you are the one responsible for maintaining / enhancing it. – GhostCat Feb 27 '17 at 08:21
  • @GhostCat I know, I barely use regexes in actual production code, except for some validation / formatting. But as I mentioned in the question, this is mainly for code-golf challenges (for everyone's information: code-golf is solving a certain challenge in as few bytes as possible). It will probably be shorter to hardcode or use a for-loop in the end, but when I was doing the challenge I was mainly interested to see it it's even possible to replace a digit with that amount of a certain character with a one-liner (hence this question). It's more out of curiosity than practical use. – Kevin Cruijssen Feb 27 '17 at 08:27
  • 1
    Then I would suggest to try your luck here: http://codegolf.stackexchange.com/ – GhostCat Feb 27 '17 at 08:29
  • 2
    No, it is not possible with a regex one-liner in Java. – Wiktor Stribiżew Feb 27 '17 at 08:34
  • Here is a link to a useful question which gives a regex which might help you: http://stackoverflow.com/questions/8270784/how-to-split-a-string-between-letters-and-digits-or-between-digits-and-letters – Tim Biegeleisen Feb 27 '17 at 08:34
  • If Wiktor says it can't be done in one line, I'd forget about it and look for an alternative, possibly one involving just a few lines. – Tim Biegeleisen Feb 27 '17 at 08:34
  • You may have a look at [this demo](http://ideone.com/Dt2pGl) to see how it can be implemented with a regex. – Wiktor Stribiżew Feb 27 '17 at 09:16

1 Answers1

0

If you really want to have it as a one-liner. A possible solution (see it more as a PoC) could be to use the Stream API.

String input = "test3something8";
input.chars()
    .mapToObj(
        i -> i >= '0' && i <= '9' ? 
            new String(new char[i-'0']).replace('\0', 'X') 
            : "" + ((char)i)
    )
    .forEach(System.out::print);

output

testXXXsomethingXXXXXXXX

note No investigation has been done for performance, scalability, to be GC friendly, etc.

SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • What about if the number more than 9. e.g. `String input = "test30something18"; ` – nanangarsyad Feb 19 '18 at 12:28
  • @Nanangarsyad The original request was `replace **digits** in a String` not numbers. And my answer was provided only to fulfil the `Does anyone know a one-liner`-requirement. If you want to replace numbers in a string by the same amount of a replacement character you should look for a solution better fitting to your problem. You can raise a new question if no related answer on SO solves your problem. – SubOptimal Feb 20 '18 at 12:20