Home > Software engineering >  Change all letters except space from a string using Java
Change all letters except space from a string using Java

Time:05-19

I want to change all letters from a string to "-" char except space using Java.

I tried:

String out = secretWord.replaceAll("^ " , "-");

and

String out = secretWord.replaceAll("\\s" , "-");

They didn't work.

I tried:

String newWord = secretWord.replaceAll("[A-Z]" , "-");

It worked but i didn't change Turkish characters I use in that string.

CodePudding user response:

Use a character class

String out = secretWord.replaceAll("[^ ]" , "-");

or a capital S, instead of a lower s to replace all non space chars

String out2 = secretWord.replaceAll("\\S" , "-");

CodePudding user response:

You can use the \\S regex:

String s = "Sonra görüşürüz";
String replaced = s.replaceAll("\\S", "-");
System.out.println(replaced); // outputs ----- ---------

CodePudding user response:

NOT needs to be expressed in square brackets in java.util.regex.Pattern:

String out = secretWord.replaceAll("[^\\s]", "-")
  •  Tags:  
  • java
  • Related