Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all characters in a Java string with stars

Tags:

java

regex

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.

like image 683
anonymous Avatar asked Sep 06 '11 10:09

anonymous


People also ask

How do you replace a string with a star?

str = str. replaceAll("(? s).", "*");

How do you replace all letters in Java?

replaceAll("[a-zA-Z]","@"); If you want to replace all alphabetical characters from all locales, use the pattern \p{L} .

How do you replace multiple occurrences of a string in Java?

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.


1 Answers

Java 11 and later

str = "*".repeat(str.length()); 

Note: This replaces newlines \n with *. If you want to preserve \n, see solution below.

Java 10 and earlier

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.

like image 187
aioobe Avatar answered Sep 20 '22 19:09

aioobe