我无法找到适当的正则表达式模式,以匹配以下各种变体:
regular expression
regular-expression
regular:expression
regular&expression
我提供了以下字符串,我需要使用findall()方法来匹配上面列出的每个出现:
str="This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression"
答案 0 :(得分:0)
import re
str= (
'This is a string to search for a regular expression '
'like regular expression or regular-expression or '
'regular:expression or regular&expression'
)
r = re.compile(r'regular[- &:]expression')
print(r.findall(str))
结果:
['regular expression', 'regular expression',
'regular-expression', 'regular:expression',
'regular&expression']
答案 1 :(得分:0)
正确的正则表达式将是“ regular [-:&] expression”,如下所示
import re
search_string='''This is a string to search for a regular expression like regular
expression or regular-expression or regular:expression or regular&expression'''
pattern = 'regular[-:&]expression'
match1= re.findall(pattern, search_string)
if match1 != None:
print(pattern+' matched')
else:
print(pattern+' did not match')
输出:
regular[-:&]expression matched
答案 2 :(得分:0)
这是通过以下方式完成的:
import re
search_string='''This is a string to search for a regular expression like regular
expression or
regular-expression or regular:expression or regular&expression'''
results1 = re.sub ("regular[ -:&]expression","regular expression", search_string)
print (results1)