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]", "");
      System.out.println(s);
  }

}