您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

匹配多行的Python正则表达式(re.DOTALL)

匹配多行的Python正则表达式(re.DOTALL)

使用先行查找将所有内容匹配 下一部分标题或字符串的末尾:

re_sections=re.compile(r"(?P<section>Section\d)\s*(?P<section_data>.+?)(?=(?:Section\d|$))", re.DOTALL)

请注意,这也需要一个非贪婪的.+?方法,否则它仍然会一直匹配到最后。

演示:

>>> re_sections=re.compile(r"(?P<section>Section\d)\s*(?P<section_data>.+?)(?=(?:Section\d|$))", re.DOTALL)
>>> for m in re_sections.finditer(text): print m.groupdict()
... 
{'section': 'Section1', 'section_data': 'stuff belonging to section1\nstuff belonging to section1\nstuff belonging to section1\n'}
{'section': 'Section2', 'section_data': 'stuff belonging to section2\nstuff belonging to section2\nstuff belonging to section2'}
python 2022/1/1 18:35:02 有226人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶