+

Python | A program that matches a word containing “g” followed by one or more e characters using a regular expression

For a given string, the task is to check if that string contains any character g, followed by one or more e, otherwise print "No matches".

Examples:

  Input:  geeks for geeks  Output:  geeks geeks  Input:  graphic era  Output:  No match 

Approach: First create a regex object (regex expression) that matches a word containing "g" followed by one or more "e" characters, and then pass the string to the findall method. This method returns a list of matched strings. Scroll through the list and type each word that matches.

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.

The implementation is as follows:

# Python program that matches the word
# contains a" g "followed by one or
# more e uses regular expressions

 
# import re packages

import re

 
# Function to check if any word # a line containing & # 39; g & # 39; followed by
# one or more

def check (string):

 

  

  # Regex / w * ge + / w * will match

# text that contains & # 39; g & # 39;, followed by

# one or more & # 39; e & # 39;

regex = re. compile ( "ge + w *" )

 < / p>

# The findall () method returns everything

  # matching regex pattern strings

  match_object = regex.findall (string)

 

# If match_object length is not equal

# equal to zero, then it contains

# matching string

  if len (match_object)! = 0 :

 

# loop through 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"

 

# Call the check function

check (string)

Output:

 geeks geeks 
Get Solution for free from DataCamp guru