Open In App

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

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




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

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads