w3resource

Java: Remove all non-alphanumeric characters from a given string


21. Remove Non-Alphanumeric

Write a Java program to remove all non-alphanumeric characters from a given string.

Sample Solution-1:

Java Code:

public class test {
 
   public static void main(String[] args) {	   
	    String text ="Java Exercises";
		System.out.println("Original string: "+text);
		System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text));
	    text ="Ex@^%&%(ercis*&)&es";
		System.out.println("\nOriginal string: "+text);
		System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text));	
        }

   public static String validate(String text) {
        return text.replaceAll("(?i)[^A-Z]", "");
   }
}

Sample Output:

Original string: Java Exercises
After removing all non-alphanumeric characters from the said string: JavaExercises

Original string: Ex@^%&%(ercis*&)&es
After removing all non-alphanumeric characters from the said string: Exercises

Pictorial Presentation:

Java Regular Expression: Remove all non-alphanumeric characters from a given string.

Flowchart :

Flowchart: Remove all non-alphanumeric characters from a given string.

Sample Solution-2:

Java Code:

public class test {
 
   public static void main(String[] args) {	   
	    String text ="Java Exercises";
		System.out.println("Original string: "+text);
		System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text));
	    text ="Ex@^%&%(ercis*&)&es";
		System.out.println("\nOriginal string: "+text);
		System.out.println("After removing all non-alphanumeric characters from the said string: "+validate(text));	
        }

   public static String validate(String text) {
        return text.replaceAll("[^a-zA-Z]", "");
   }
}

Sample Output:

Original string: Java Exercises
After removing all non-alphanumeric characters from the said string: JavaExercises

Original string: Ex@^%&%(ercis*&)&es
After removing all non-alphanumeric characters from the said string: Exercises

Flowchart :

Flowchart: Remove all non-alphanumeric characters from a given string.


For more Practice: Solve these Related Problems:

  • Write a Java program to filter a string to only include letters and digits using regex replacement.
  • Write a Java program to iterate through a string and construct a new string containing only alphanumeric characters.
  • Write a Java program to implement a method that strips out punctuation and symbols from a string.
  • Write a Java program to compare the output of regex-based non-alphanumeric removal with manual character filtering.

Go to:


PREV : Add Thousand Separator.

NEXT : Validate Phone Number.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.