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?