Python|使用正则表达式匹配包含“g”后跟一个或多个 e 的单词的程序
先决条件:正则表达式 |第 1 组,第 2 组
给定一个字符串,任务是检查该字符串是否包含任何g后跟一个或多个e ,否则,打印 No match。
例子 :
Input : geeks for geeks
Output : geeks
geeks
Input : graphic era
Output : No match
方法:首先,创建一个正则表达式(regex)对象来匹配一个包含'g'后跟一个或多个e的单词,然后在findall
方法中传递一个字符串。此方法返回匹配字符串的列表。循环遍历列表并打印每个匹配的单词。
\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.
下面是实现:
# Python program that matches a word
# containing ‘g’ followed by one or
# more e’s using regex
# import re packages
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 length of match_object is not
# equal to zero then it contains
# matched string
if len(match_object) != 0 :
# looping 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"
# Calling check function
check(string)
输出 :
geeks
geeks