繁体   English   中英

Python正则表达式,用于查找具有多个变体的字符串的所有出现

[英]Python regular expression to find all occurences of a string with multiple variations

我找不到合适的正则表达式模式来匹配以下每个变体:

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"
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']

正确的正则表达式将是“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 

这是通过以下方式完成的:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM