Java alphanumeric patterns: How to remove non-alphanumeric characters from a Java String

Java String "alphanumeric" tip: How to remove non-alphanumeric characters from a Java String.

Here's a sample Java program that shows how you can remove all characters from a Java String other than the alphanumeric characters (i.e., a-Z and 0-9). As you can see, this example program creates a String with all sorts of different characters in it, then uses the replaceAll method to strip all the characters out of the String other than the patterns a-zA-Z0-9. The code essentially deletes every other character it finds in the string, leaving only the alphanumeric characters.

package foo;

public class StringTest {

  public static void main(String[] args) {
      String s = "yo-dude: like, ... []{}this is a string";
      s = s.replaceAll("[^a-zA-Z0-9]", "");




Thanks a lot.


You are a life saver.


Thanks bro you save my life! Simple way to code!

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.