regex python正则表达式贪婪捕获[重复]

50pmv0ei  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(100)

此问题在此处已有答案

Match text between two strings with regular expression(3个答案)
Python - single vs multiline REGEX(1个答案)
18天前关门了。
我需要将以下多行文本中AAA和BBB之间的整个文本(不包括那些)替换为空白。我尝试了此模式=> 'This form.*[^Accuracy.]Accuracy.'但它只能捕获到第一个'Accuracy.'我试图做一个贪婪的捕获,但无法获得正确的模式。请帮助。

import re
haystack='''Other needs and/or restrictions:
Telephone visit on 11/16 @ 3:50 PM 
AAA This form has been electronically signed. 
Check for Accuracy. XXX authorized by Dr Zhivago (M.D.) 
This form contains your private health information that 
you may choose to release to another party; 
please review for Accuracy. 
BBB
'''
pattern = 'This form.*[^Accuracy\.]Accuracy\.'
p = re.compile(pattern, re.MULTILINE)
match = p.search(haystack)
if match != None:
    haystack = re.sub(pattern,'',haystack,re.MULTILINE)
    print(haystack)

字符串

xzabzqsa

xzabzqsa1#

下面是捕获AAA和BBB之间的所有字符串:

import re

text = '''Other needs and/or restrictions:
Telephone visit on 11/16 @ 3:50 PM 
AAA This form has been electronically signed. 
Check for Accuracy. XXX authorized by Dr Zhivago (M.D.) 
This form contains your private health information that 
you may choose to release to another party; 
please review for Accuracy. 
BBB'''

pattern = re.compile(r'AAA(.*?)BBB', re.DOTALL)
matches = pattern.findall(text)

for match in matches:
    print(match.strip())

字符串

相关问题