Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Accept the Strings Which Contains all Vowels
Next article icon

Python Regex – Program to accept string starting with vowel

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Regular expression in Python
Given a string, write a Python program to check whether the given string is starting with Vowel or Not.
Examples: 

   Input: animal Output: Accepted  Input: zebra Output: Not Accepted

In this program, we are using search() method of re module.
re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. 
Let’s see the Python program for this : 
 

Python3




# Python program to accept string starting with a vowel
 
# import re module
 
# re module provides support
# for regular expressions
import re
 
# Make a regular expression
# to accept string starting with vowel
regex = '^[aeiouAEIOU][A-Za-z0-9_]*'
     
# Define a function for
# accepting string start with vowel
def check(string):
 
     # pass the regular expression
     # and the string in search() method
    if(re.search(regex, string)):
        print("Valid")
         
    else:
        print("Invalid")
     
 
# Driver Code
if __name__ == '__main__' :
     
    # Enter the string
    string = "ankit"
     
    # calling run function
    check(string)
 
    string = "geeks"
    check(string)
 
    string = "sandeep"
    check(string)
 
 
Output: 
Valid Invalid Invalid

 

Using re.findall:

We are using the re module to work with regular expressions in Python. The re.findall method is used to search for all the occurrences of the regular expression in the given string. If a match is found, it returns a list containing the matches. If no match is found, it returns an empty list.

We have defined a regular expression to match strings that start with a vowel (either uppercase or lowercase). The regular expression ‘^[aeiouAEIOU][A-Za-z0-9_]*’ means:

  • ^ matches the start of a string
  • [aeiouAEIOU] matches any of the characters a, e, i, o, u, A, E, I, O, U
  • [A-Za-z0-9_]* matches any character in the range A-Z, a-z, 0-9, or _, zero or more times

We pass the regular expression and the string to the re.findall method. If a match is found, the match variable will contain a list with the matching string. If no match is found, the match variable will be an empty list. We can then check if the match variable is non-empty to determine if the string starts with a vowel or not.

Python3




# Python program to accept string starting with a vowel
import re
 
def check(string):
    # Make a regular expression to accept string starting with vowel
    regex = '^[aeiouAEIOU][A-Za-z0-9_]*'
     
    # Use the findall method to search for the regular expression in the string
    match = re.findall(regex, string)
     
    if match:
        print("Valid")
    else:
        print("Invalid")
 
# Driver Code
if __name__ == '__main__' :
      
    # Enter the string
    string = "ankit"
      
    # calling run function
    check(string)
  
    string = "geeks"
    check(string)
  
    string = "sandeep"
    check(string)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
Valid Invalid Invalid

Time complexity: O(n) where n is the length of the string
Auxiliary Space: O(n)

Approach#3: Using re.match()

This approach problem can be solved using regular expressions. We create a pattern that matches strings starting with any vowel (lowercase or uppercase). Then, we use re.match to check if the given string matches the pattern. If it does, we return “Accepted”. Otherwise, we return “Not Accepted”.

Algorithm

1. Define the function starts_with_vowel that takes a string s as input.
2. Create a pattern that matches strings starting with any vowel (lowercase or uppercase).
3. Use re.match to check if the given string s matches the pattern.
4. If s matches the pattern, return “Accepted”. Otherwise, return “Not Accepted”.

Python3




import re
 
def starts_with_vowel(s):
    """Return 'Accepted' if `s` starts with a vowel, 'Not Accepted' otherwise."""
    pattern = '^[aeiouAEIOU].*'
    if re.match(pattern, s):
        return "Accepted"
    else:
        return "Not Accepted"
 
# Example usage:
s1 = "animal"
s2 = "zebra"
print(starts_with_vowel(s1))  # Output: Accepted
print(starts_with_vowel(s2))  # Output: Not Accepted
 
 
Output
Accepted Not Accepted 

Time complexity: O(n), where n is the length of the input string s. This is because we are using the re.match() function, which takes linear time to match the pattern with the input string.

Space complexity: O(1), as we are only creating a single regular expression pattern and a few string variables that do not scale with the input size.



Next Article
Python Program to Accept the Strings Which Contains all Vowels
author
ankthon
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Regex-programs
  • python-regex
Practice Tags :
  • python

Similar Reads

  • Python Program to Accept the Strings Which Contains all Vowels
    The problem is to determine if a string contains all the vowels: a, e, i, o, u. In this article, we’ll look at different ways to solve this. Using all()all() function checks if all vowels are present in the string. It returns True if every condition in the list comprehension is met. [GFGTABS] Python
    2 min read
  • Python Program that Extract words starting with Vowel From A list
    Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u). Input : test_list = ["all", "love", "get", "educated", "by", "gfg"] Output : ['all', 'educated'] Explanation : a, e are vowels, hence words extracted.Input : test_list = ["all", "
    5 min read
  • Python Regex | Program to accept string ending with alphanumeric character
    Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples: Input: ankitrai326 Output: Accept Input: ankirai@ Output: Discard In this program, we are using search() method of re module.
    2 min read
  • Python Program to Count characters surrounding vowels
    Given a String, the task is to write a Python program to count those characters which have vowels as their neighbors. Examples: Input : test_str = 'geeksforgeeksforgeeks' Output : 10 Explanation : g, k, f, r, g, k, f, r, g, k have surrounding vowels. Input : test_str = 'geeks' Output : 2 Explanation
    3 min read
  • Python Program to Count the Number of Vowels in a String
    In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first des
    10 min read
  • Python - Replace vowels in a string with a specific character K
    The task is to replace all the vowels (a, e, i, o, u) in a given string with the character 'K'. A vowel can be in uppercase or lowercase, so it's essential to account for both cases when replacing characters. Using str.replace() in a LoopUsing str.replace() in a loop allows us to iteratively replace
    3 min read
  • Python Program to Replace all Occurrences of ‘a’ with $ in a String
    Given a string, the task is to write a Python program to replace all occurrence of 'a' with $. Examples: Input: Ali has all aces Output: $li h$s $ll $ces Input: All Exams are over Output: $ll Ex$ms $re Over Method 1: uses splitting of the given specified string into a set of characters. An empty str
    3 min read
  • Recursively Count Vowels From a String in Python
    Python is a versatile and powerful programming language that provides various methods to manipulate strings. Counting the number of vowels in a string is a common task in text processing. In this article, we will explore how to count vowels from a string in Python using a recursive method. Recursion
    3 min read
  • Python program to check if given string is vowel Palindrome
    Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
    5 min read
  • Python Program To Check String Is Palindrome Using Stack
    A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str =
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences