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:");
         System.out.println(str);
         System.out.println("------------------------------------");
         // Using regular expressions to remove non ascii characters
         str = str.replaceAll("[^\p{ASCII}]", "");
         System.out.println("After removing non ASCII characters:");
         System.out.println(str);
     }
 }

When you run above program, you will get below output:

Before removing non ASCII characters:
jå∫∆avµa2bl√øog
------------------------------------
After removing non ASCII characters:
java2blog

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.