Home > Blockchain >  Why is the replace all method not working?
Why is the replace all method not working?

Time:02-25

I am testing out the replaceAll() method of the String class and I am having problems with it.

I do not understand why my code does not replace whitespaces with an empty string.

Here's my code:

public static void main(String[] args) {
    String str = " I like pie!@!@!      It's one of my favorite things !1!!!1111";
    str = str.toLowerCase();
    str = str.replaceAll("\\p{Punct}", "");
    str = str.replaceAll("[^a-zA-Z]", "");
    str = str.replaceAll("\\s ", " ");
    System.out.print(str);

}

Output:

ilikepieitsoneofmyfavoritethings

CodePudding user response:

The problem is there are no whitespaces in your String after this:

str = str.replaceAll("[^a-zA-Z]", "");

which replaces all characters that are not letters, which includes whitespaces, with a blank (effectively deleting it).

Add whitespace to that character class so they don't get nuked:

str = str.replaceAll("[^a-zA-Z\\s]", "");

And this line may be deleted:

str = str.replaceAll("\\p{Punct}", "");

because it's redundant.

Final code:

String str = " I like pie!@!@!      It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("[^a-zA-Z\\s]", "");
str = str.replaceAll("\\s ", " ");
System.out.print(str);

Output:

 i like pie its one of my favorite things 

You may want to add str = str.trim(); to remove the leading space.

  • Related