Python | Program that matches a word containing ‘g’ followed by one or more e’s using regex
Last Updated :
27 Jan, 2023
Prerequisites : Regular Expressions | Set 1, Set 2 Given a string, the task is to check if that string contains any g followed by one or more e’s in it, otherwise, print No match. Examples :
Input : geeks for geeks
Output : geeks
geeks
Input : graphic era
Output : No match
Approach : Firstly, make a regular expression (regex) object that matches a word which contains ‘g’ followed by one or more e’s, then pass a string in the findall method. This method returns the list of the matched strings. Loop through the list and print each matched word.
\w – represent Any letter, numeric digit, or the underscore character. * means zero or more occurrence of the character. + means one or more occurrence of the character.
Below is the implementation :
Python3
import re
def check(string) :
regex = re. compile ("ge + \w * ")
match_object = regex.findall(string)
if len (match_object) ! = 0 :
for word in match_object :
print (word)
else :
print ("No match")
if __name__ = = '__main__' :
string = "Welcome to geeks for geeks"
check(string)
|
Output :
geeks
geeks
Time complexity: O(n) where n is the length of the input string
Auxiliary Space: O(1), as the program uses a constant amount of memory for the regex pattern and the match_object.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...