Remove all non-alphabetical characters of a String in Java?

ProgrammingJavaObject Oriented Programming

The split() method of the String class accepts a String value representing the delimiter and splits into array of tokens (words), treating the string between the occurrence of two delimiters as one token.

For example if you pass single space “ ” as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String.

If the String does not contain the specified delimiter this method returns an array containing the whole string as element.

The regular expression “\\W+” matches all the not alphabetical characters (punctuation marks, spaces, underscores and special symbols) in a string.

Therefore, to remove all non-alphabetical characters from a String −

  • Get the string.

  • Split the obtained string int to an array of String using the split() method of the String class by passing the above specified regular expression as a parameter to it.

  • This splits the string at every non-alphabetical character and returns all the tokens as a string array.

  • Join all the elements in the obtained array as a single string.


 Live Demo

import java.util.Scanner;
public class RemovingAlphabet {
   public static void main(String args[]) {
      Scanner sc = new Scanner(;
      System.out.println("Enter your name: ");
      String str = sc.nextLine();
      String[] stringArray = str.split("\\W+");
      String result = new String();
      for(int i = 0; i < stringArray.length;i++){
         result = result+ stringArray[i];
      System.out.println("Result: "+result);


Enter your name:
Krishna ^% Kasyap*@#
Result: KrishnaKasyap
Published on 14-Oct-2019 08:52:02