Multiline python regex

天涯浪子 提交于 2020-05-14 19:09:57

问题


I have a file structured like this :

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

I'm trying to find the regex that will split my file like this :

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

So far, I've ended up with the following :

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

The multiline text is not catched. I guess is because the lazy qualifier is really lazy and catch nothing, but I take it out, the regex gets really greedy :

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

Does any one has an idea ? Thanks !


回答1:


You could tell the regex to stop matching at the next line that starts with A: (or at the end of the string):

re.findall(r'A:(.*?)\nB:(.*?)\n(.*?)(?=^A:|\Z)', f.read(), re.DOTALL|re.MULTILINE)


来源:https://stackoverflow.com/questions/12800056/multiline-python-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!