Python | Program that matches a word containing ‘g’ followed by one or more e’s using regex

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program that matches a word
# containing ‘g’ followed by one or
# more e’s using regex
  
# import re pakages
import re
  
# Function check if the any word of
# the string containing 'g' followed
# by one or more e's
def check(string) :
  
      
    # Regex \w * ge+\w * will match 
    # text that contains 'g', followed 
    # by one or more 'e'
    regex = re.compile("ge+\w*")
  
    # The findall() method returns all 
    # matching strings of the regex pattern
    match_object = regex.findall(string)
  
    # If lenght of match_object is not
    # equal to zero then it contains
    # matched string
    if len(match_object) != 0 :
  
        # looping throgh the list
        for word in match_object :
            print(word)
              
    else :
        print("No match")
  
  
# Driver Code     
if __name__ == '__main__' :
  
    # Enter the string
    string = "Welcome to geeks for geeks"
  
    # Calling check function
    check(string)

chevron_right


Output :

geeks
geeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.