I want to replace all the characters in a Java String with *
character. So it shouldn't matter what character it is, it should be replaced with a *
.
I know there are heaps of examples there on internet but have not one that replaces every character and I have tried myself but no success.
str = str. replaceAll("(? s).", "*");
replaceAll("[a-zA-Z]","@"); If you want to replace all alphabetical characters from all locales, use the pattern \p{L} .
You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.
str = "*".repeat(str.length());
Note: This replaces newlines \n
with *
. If you want to preserve \n
, see solution below.
str = str.replaceAll(".", "*");
This preserves newlines.
To replace newlines with *
as well in Java 10 and earlier, you can use:
str = str.replaceAll("(?s).", "*");
The (?s)
doesn't match anything but activates DOTALL
mode which makes .
also match \n
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With