Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the replace all method not working?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading