Replace Special Characters Using Java

Target Audience: Java Programmers

What should you know already? Basics of Java

Have you ever been tried to replace all special characters in a String? If you had, you may know replace() and replaceAll() methods. Of course, both methods replaces all occurrences of specified strings.

replace() and replaceAll()

See the following examples:

String str=”blaaah”;
str=str.replace(“a”,”one”);

The above code outputs bloneoneoneh.

String str=”blaaah”;
str=str.replaceAll(“a”,”one”);

This also gives output bloneoneoneh. So, what is the difference between replace() and replaceAll() methods? replaceAll() method uses regular expression for searching the replacement portion in the String object. Assume that you are in a situation of replacing all special characters with empty (“”). What will you do? Will you use replace() or replaceAll()? The following code replaces all special characters in a String:

String str=”hai ? i @c / \ ho(w) : are ^ you ??”;
System.out.println(str);
str = str.replaceAll(“[^a-zA-Z 0-9]+”,””);
System.out.println(str);

The above code gives the following output:

hai ? i @c / ho(w) : are ^ you ??
hai i c how are you

What if you try to do this using replace() method? It will not give the result as you expected. Because it deals with String constant, where as replaceAll() deals with Regular Expression.

Regular Expression is very flexible. Suppose you want to replace all special characters other than ( and ), then the code will be:

str = str.replaceAll(“[^a-zA-Z 0-9()]+”,””);

It will give the following output:
hai c ho(w) are you

Of course, your valuable comments and feedback are most welcome.

References

Permanent link to this article: https://blog.openshell.in/2011/03/replacing-special-characters-using-java/

Leave a Reply

Your email address will not be published.