Tuesday 9 February 2016

How to remove all special characters from String in Java

You can use regular expression and replaceAll() method of java.lang.String class to remove all special characters from String. A special character is nothing but characters like ! #, % etc. Precisely, you need to define what is a special character for you. Once you define that you can use a regular expression to replace those character with empty String, which is equivalent to removing all special characters from String. For example, suppose, your String contains some special characters e.g. "Awesome!!!" and you want to remove those !!! to reduce some excitement, you can use replaceAll("!", "") to get rid of all exclamation mark from String. Similarly, if you String contains many special characters, you can remove all of them by just picking alphanumeric characters e.g. replaceAll("[^a-zA-Z0-9_-]", ""), which will replace anything with empty String except a to z, A to Z, 0 to 9,_ and dash. Let's see couple fo examples to remove all special characters from String in Java.
Read more »

No comments:

Post a Comment