How to Validate if a String Starts with a Vowel Using Regex in Java?
Last Updated :
25 Jan, 2024
Regular Expressions in Java allow developers to create patterns for matching strings. In this article, we will learn How to Check whether the Given Character String Starts with a Vowel.
Example to Check String is Starting with a Vowel
Input: “Apple”
Output: Is a Vowel
Input: “Cart”
Output: Is not a Vowel
Program Regex Check whether the Given Character String Starts with a Vowel
Let’s delve into detailed examples to understand the application of regex for checking if a string starts with a vowel.
Java
import java.util.regex.*;
public class Temp {
public static void main(String[] args)
{
String[] inputStrings = { "Apple" , "Bat" , "Cat" , "Orange" };
String regexPattern = "^(?i)[aeiou].*" ;
for (String Temp : inputStrings) {
if (Temp.matches(regexPattern)) {
System.out.println(Temp+ " starts with Vowel" );
}
else {
System.out.println(Temp+ " does not start with a vowel." );
}
}
}
}
|
Output
The string starts with a vowel.
Explaination of the above Program:
-^(?i)[aeiou].* is the regular expression used for pattern matching:
- ^ asserts the start of the string.
- (?i) enables case-insensitive matching.
- [aeiou] matches any one of the lowercase vowels.
- .* matches any sequence of characters (zero or more).
The matches method is called on the inputString with the specified regular expression pattern.cIf the input string matches the pattern, it prints “The string starts with a vowel.” Otherwise, it prints “The string does not start with a vowel.”
Share your thoughts in the comments
Please Login to comment...