How to remove non-ascii characters from a string in java

In this post, we will see how to remove non ascii character from a string in java.
Sometimes, you get non-ascii characters in String and you need to remove them. We will use regular expressions to do it.

Java program to remove non-ascii characters:

package org.arpit.java2blog;

public class StringRemoveASCIIMain {
     public static void main(String a[]){
         String str = "jå∫∆avµa2bl√øog";
         System.out.println("Before removing non ASCII characters:");
         // Using regular expressions to remove non ascii characters
         str = str.replaceAll("[^\\p{ASCII}]", "");
         System.out.println("After removing non ASCII characters:");

When you run above program, you will get below output:
Before removing non ASCII characters:
After removing non ASCII characters:

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012