如何在python中使用regex在多个句子的段落中搜索模式



我有一段'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day. '。如果可能的话,我想要一个RegEx来在一个表达式的完整段落中查找'Hello my name is xyz how may I help you today''have a nice day'。在这两个短语之间,我想找到的单词/句子可以是任意数量的。

您可以使用re.findall来查找匹配的字符串。re.findall将返回一个包含匹配项的列表。然后,您可以使用if语句来查找列表是否不为空,从而是否至少包含一个匹配项。另外,不要忘记使用re.IGNORECASE,以忽略区分大小写的行为。下面是匹配项和非匹配项的示例。

import re
txt = 'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day. '
negative_txt = 'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a terrible day. '

print('for the txt')
my_name_is = re.findall('HeLlO mY nAmE is', txt, flags=re.IGNORECASE)
nice_day = re.findall('have a nice day', txt, flags=re.IGNORECASE)
if my_name_is and nice_day:
print("the sentences 'Hello my name is', and 'have a nice day', are present")
else:
print("the sentence 'Hello my name is' or 'have a nice day', are NOT present")
print('for the negative txt')  
my_name_is = re.findall('Hello my name is', negative_txt, flags=re.IGNORECASE)
nice_day = re.findall('have a nice day', negative_txt, flags=re.IGNORECASE)
if my_name_is and nice_day:
print("the sentences 'Hello my name is', and 'have a nice day', are present")
else:
print("the sentence 'Hello my name is' or 'have a nice day', are NOT present")

您只需使用.*,其中.匹配任何字符,而*是零或更多运算符。

Hello my name is .* how may I help you today.*have a nice day

此外,我想您可能想在搜索中添加IGNORECASE标志。

最终的代码是这样的:

import re
my_text = "Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day."
my_regex = r"Hello my name is .* how may I help you today.*have a nice day"
if re.search(my_regex, my_text, re.IGNORECASE) :
print("OK")

最新更新