Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package.
For any string, here the task is to check whether a string contains only alphabets or not using Regex. Now for a given string, the characters of the string are checked one by one using Regex. Regex can be used to check a string for alphabets. String.matches() method is used to check whether or not the string matches the given regex.
^[a-zA-Z]*$
Illustrations:
Input: Lazyroar Output: True Input: Geeks4Geeks Output: False Input: null Output: False
Algorithm
- Get the string
- Match the string with the Regex using matches().
- Return true is matched
Pseudocode for the above algorithm is proposed below as follows:
public static boolean isStringOnlyAlphabet(String str) { return ((!str.equals("")) && (str != null) && (str.matches("^[a-zA-Z]*$"))); }
Example:
Java
// Java Program to Check If String Contains Only Alphabets // Using Regular Expression // Main class class GFG { // Method 1 // To check String for only Alphabets public static boolean isStringOnlyAlphabet(String str) { return ((str != null ) && (!str.equals( "" )) && (str.matches( "^[a-zA-Z]*$" ))); } // Method 2 // Main driver method public static void main(String[] args) { // Calling out methods over string // covering all scenarios // Use case 1 System.out.println( "Test Case 1:" ); // Input string String str1 = "Lazyroar" ; System.out.println( "Input: " + str1); System.out.println( "Output: " + isStringOnlyAlphabet(str1)); // Use case 2 // Checking for String with numeric characters System.out.println( "\nTest Case 2:" ); // Input string String str2 = "Geeks4Geeks" ; System.out.println( "Input: " + str2); System.out.println( "Output: " + isStringOnlyAlphabet(str2)); // Use Case 3 // Checking for null String System.out.println( "\nTest Case 3:" ); // Input string String str3 = null ; System.out.println( "Input: " + str3); System.out.println( "Output: " + isStringOnlyAlphabet(str3)); // Use Case 4 // Checking for empty String System.out.println( "\nTest Case 4:" ); // Input string String str4 = "" ; System.out.println( "Input: " + str4); System.out.println( "Output: " + isStringOnlyAlphabet(str4)); } } |
Test Case 1: Input: Lazyroar Output: true Test Case 2: Input: Geeks4Geeks Output: false Test Case 3: Input: null Output: false Test Case 4: Input: Output: false
Related Articles: