Remove All Special Character from String in Java


In Java, to remove all special character form a given string, we can use the replaceAll(String regex, String replacement) method of String class. replaceAll(regex, replacement) replaces each substring of this string that matches the given regular expression with the given replacement.

Have a look on below example:

RemoveSpecialCharacters.java
package org.websparrow;

public class RemoveSpecialCharacters {

    public static void main(String[] args) {

        String str = "!W@eb#s$pa%rr*,o:w";

        String finalStr = str.replaceAll("[^0-9a-zA-Z]", "");

        System.out.println("Original string: " + str);
        System.out.println("Final string: " + finalStr);
    }
}

Note: The regular expression [^0-9a-zA-Z] matches any character that is not a letter(uppercase or lowercase) or a number.

Output:

Original string: !W@eb#s$pa%rr*,o:w
Final string: Websparrow

References

  1. String.replaceAll – Java Doc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.