多行 python 正则表达式

2024-01-06

我有一个结构如下的文件:

A: some text
B: more text
even more text
on several lines
A: and we start again
B: more text
more
multiline text

我正在尝试找到将我的文件分割为这样的正则表达式:

>>>re.findall(regex,f.read())
[('some text','more text','even more text\non several lines'),
 ('and we start again','more text', 'more\nmultiline text')]

到目前为止,我已经得到以下结果:

>>>re.findall('A:(.*?)\nB:(.*?)\n(.*?)',f.read(),re.DOTALL)
[(' some text', ' more text', ''), (' and we start again', ' more text', '')]

多行文本未被捕获。我想是因为惰性限定符真的很懒并且什么也没捕获,但是我把它拿出来,正则表达式变得非常贪婪:

>>>re.findall('A:(.*?)\nB:(.*?)\n(.*)',f.read(),re.DOTALL)
[(' some text',
' more text',
'even more text\non several lines\nA: and we start again\nB: more text\nmore\nmultiline text')]

有人有想法吗?谢谢 !


您可以告诉正则表达式在以以下开头的下一行停止匹配A:(或在字符串末尾):

re.findall(r'A:(.*?)\nB:(.*?)\n(.*?)(?=^A:|\Z)', f.read(), re.DOTALL|re.MULTILINE)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多行 python 正则表达式 的相关文章

随机推荐