English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java regular expressions for checking if a string contains letters

The following is a regular expression to match letters in the given input-

"^[a-zA-Z]*$"

where,

  • ^ matches the beginning of a sentence.

  • [a-zA-[a] matches lowercase and uppercase letters.

  • *represents zero or more times.

  • & represents the end of a line.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ContainsAlphabetExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String names[] = new String[5];
      for (int i = 0; i < names.length; i++{
         System.out.println("Enter your name: ");
         names[i] = sc.nextLine();
      }
      //Regular expression for accepting English letters
      String regex = "^[a-zA-Z]*$";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      for (String name : names) {
         //Create a Matcher object
         Matcher matcher = pattern.matcher(name);
         if(matcher.matches()) {}}
            System.out.println(name+") is a valid name);
         } else {
            System.out.println(name+") is not a valid name);
         }
      }
   }
}

Output Result

Enter your name:
krishna
Enter your name:
kasyap
Enter your name:
maruthi#
Enter your name:
Sai_Ram
Enter your name:
Vani.Viswanath
krishna is a valid name
kasyap is a valid name
maruthi# is not a valid name
Sai_Ram is not a valid name
Vani.Viswanath is not a valid name

Example2

import java.util.Scanner;
public class Just {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      String regex = "^[a-zA-Z]*$";
      boolean result = name.matches(regex);
      if(result) {
         System.out.println("Given name is valid");
      } else {
         System.out.println("Given name is not valid");
      }
   }
}

Output Result

Enter your name:
vasu#dev
Given name is not valid
You May Also Like