Devendra
Devendra

Reputation: 1884

Remove white space and special characters in Java

I have a String which contains some special characters and white spaces as well. I want to remove white spaces and special character. I am doing it as:

String str = "45,%$^ Sharma%$&^,is,46&* a$# Java#$43 Developer$#$^ in#$^ CST&^* web*&(,but he%^&^% wants to move@!$@# to another team";
System.out.println(str.replaceAll("[^a-zA-Z]", " ").replaceAll("\\s+", " "));

Output:

sharma is a Java Developer in CST web but he wants to move to another team

Can I do this using single operation? How?

Upvotes: 4

Views: 44560

Answers (4)

Almustafa Azhari
Almustafa Azhari

Reputation: 860

You can use the below to remove anything that is not a character (A-Z or a-z).

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

Upvotes: 0

TomasZ.
TomasZ.

Reputation: 469

The OR operator (|) should work:

System.out.println(str.replaceAll("([^a-zA-Z]|\\s)+", " "));

Actually, the space doesn't have to be there at all:

System.out.println(str.replaceAll("[^a-zA-Z]+", " "));

Upvotes: 4

Cephalopod
Cephalopod

Reputation: 15145

Replace any sequence of non-letters with a single white space:

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

You also might want to apply trim() after the replace.

If you want to support languages other than English, use "[^\\p{IsAlphabetic}]+" or "[^\\p{IsLetter}]+". See this question about the differences.

Upvotes: 20

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Try this:

str.replaceAll("[\\p{Punct}\\s\\d]+", " ");

Replacing punctuation, digits and white spaces with a single space.

Upvotes: 3

Related Questions