Open In App

How to Validate if a String Starts with a Vowel Using Regex in Java?

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 Program Regex Check Whether the
// Given Character String Starts with Vowel 
import java.util.regex.*;
  
// Driver Class
public class Temp {
      // Main Function
    public static void main(String[] args)
    {
          // String Array
        String[] inputStrings = {"Apple","Bat","Cat","Orange"};
          
          // Regex to check starting character
          String regexPattern = "^(?i)[aeiou].*";
  
          // Checking all the elements in Array
        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:

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.”

Article Tags :