Java - Remove all characters but letters and numbers using regular expression

By xngo on February 27, 2019

public class StrippingUnwantedChars
{
 
  public static void main(String[] args)
  {
    String s = "Good Morning, today is 1900-12-31.";
 
    /**
     * Replace characters that are NOT lowercase letters(a-z), uppercase 
     *  letters(A-Z) or numbers(0-9) with empty string.
     */
    s = s.replaceAll("[^a-zA-Z0-9]", "");
 
    System.out.println(s); // Output: GoodMorningtodayis19001231
  }
 
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.