Check if a string contains only alphabets in Java using Regex
Given a string, the task is to check whether a string contains only alphabets or not using Regex in Java.
Input: GeeksforGeeks Output: True Input: Geeks4Geeks Output: False Input: null Output: False
In this article, the characters of the string are checked one by one 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.
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.
- Get the string
- Match the string with the Regex using matches().
- Return true is matched
Below is the implementation of the above approach:
Program: Checking for String containing only Alphabets
Test Case 1: Input: GeeksforGeeks Output: true Test Case 2: Input: Geeks4Geeks Output: false Test Case 3: Input: null Output: false Test Case 4: Input: Output: false
- Check if a string contains only alphabets in Java using ASCII values
- Check if a string contains only alphabets in Java using Lambda expression
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.