Check if a String Contains only Alphabets in Java using Regex

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 classclass 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:



