首页 > 解决方案 > Python多行匹配字符串结尾

问题描述

我正在尝试匹配,直到我点击一个模式(“this”忽略行首和模式之间的任何空格)或直到段落中字符串的结尾,使用:

r'.*?(?=^[^\S\n]*this|$)'

如果我的字符串只有一行($ 匹配行尾),则此正则表达式字符串可以正常工作。但是我找不到匹配字符串结尾的正则表达式,那么有没有一种干净的方法呢?以下是我的代码:

import re  
a_str="""\  
paragraph starts here  
another line
this line may or may not exist"""  
a_match = re.compile(r'.*?(?=^[^\S\n]*this|$)', re.MULTILINE|re.DOTALL).match(a_str)

编辑

预期输出:

"paragraph starts here\nanother line"

标签: pythonregexpython-3.x

解决方案


现在可以在多行模式下用 '\Z' 表示字符串的末尾。

参考:https ://docs.python.org/3.8/library/re.html


推荐阅读