How to remove special characters from a string in java

Here we will see How to remove special characters from a string in java.

Special characters are like & $ % @ ! < > etc that may occurs in string.

To remove this we see programs how to remove special characters in java

In Java String is a class that provides different constructors and methods to manipulate strings.

To remove special characters we will use the String class method replaceAll().

String replaceAll(String regex, String replacement)

This method takes two arguments.

First is String regular expression (regex) that matched the substring that the user wants to replace.

The second is String replacement, the string which will replace with a regular expression substring.

special characters

1. How to remove special characters from a string in java example

How to remove special characters from a string in java example
Fig: How to remove special characters from a string in java example

Here a String s is having content Hello?@ Friends, how, are ^you which contains string and special symbols.

We have to remove special symbols and print the string.

Here we used replaceAll() as in the example you can see s.replaceAll(“[?@,^]*”, “”); .

You have to include all special characters inside [].

replaceAll() will replace all characters available in [] with “”.

Output

In the above program, we know that special characters ?@,^ are available in String.

2. Java remove all special characters from string

Sometimes we don’t know which special character is there.

To remove all special characters from the string we use

string.replaceAll(“[^a-zA-Z]+”,” “);

It will remove all special characters except small a-z and A-Z.

Output

It removes characters other than small and capital alphabets.

Here you can see there is a digit in a String that is also removed.

3. How to remove special character from string except digits

If you want not to remove digits then you have to modify your Regular expression.

In above example we want to remove special characters. String also contains digits we want to keep digits.

for this we have used replaceAll(“[^a-zA-Z0-9]+”,” “);.

the ^ symbols tells except a-zA-Z0-9 remove all.

Output

To achieve the above two results we can also use this

replaceAll(“[^a-zA-Z0]+”,” “);

is same as

replaceAll(“[^\\p{Alpha}]+”,””);

replaceAll(“[^a-zA-Z0-9]+”,””);

is same as

replaceAll(“^\\p{Alpha}\\p{Digit}]+”,””);

Output

4. Remove special characters from string java except few

Sometimes we want to keep some special characters with string-like comma(,) or full stop (.).

Other than this we want to remove it.

For that, we have to add these two to our regular expression as below

replaceAll(“[^a-zA-Z0-9,.]+”,” “);

Example: How to ignore special characters in java string

Output

5. Remove symbols from string java

Remove symbols from string java
Fig: Remove symbols from string java