Python Regex - Program to Accept String Starting with Vowel
Given a string, the task is to check whether it starts with a vowel (a, e, i, o, u -> uppercase or lowercase). For example:
Input: animal -> Accepted
Input: zebra -> Not Accepted
Let's explore different regex-based methods to perform this check in Python.
Using re.fullmatch()
fullmatch() checks whether the entire string follows the pattern. We simply enforce that the first character is a vowel, and allow anything after it.
import re
text = "Animal"
pattern = r"^[AEIOUaeiou].*"
if re.fullmatch(pattern, text):
print("Accepted")
else:
print("Not Accepted")
Output
Accepted
Explanation:
- ^ ensures checking starts at the beginning
- [AEIOUaeiou] means the first letter must be a vowel
- .* lets any characters appear afterward
Using re.match() with ^ Anchor
match() always checks from the beginning, so it can directly test whether the string starts with a vowel.
import re
text = "animal"
pattern = r"^[AEIOUaeiou].*"
if re.match(pattern, text):
print("Accepted")
else:
print("Not Accepted")
Output
Accepted
Using re.search() With Start Anchor
search() scans the whole string, but because the regex begins with ^, the match is only valid if the string starts with a vowel.
import re
text = "animal"
pattern = r"^[AEIOUaeiou]"
if re.search(pattern, text):
print("Accepted")
else:
print("Not Accepted")
Output
Accepted
Using re.findall()
findall() returns all parts of the string that match the pattern. Here, our pattern checks only the first character, so if the string starts with a vowel, the returned list will contain that vowel.
import re
text = "animal"
first = re.findall(r"^[AEIOUaeiou]", text)
if first:
print("Accepted")
else:
print("Not Accepted")
Output
Accepted