簡體   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