Python Regex - Program to accept string starting with vowel
Last Updated : 23 Apr, 2023
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
OutputValid 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
OutputAccepted 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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read