Python多行匹配字符串结尾

时间:2018-12-10 21:50:35

标签: python regex python-3.x

我正在尝试匹配,直到我碰到一个模式(“ 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"

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

看起来就像在前面删除多余的'| $'一样。
向前看也显然匹配字符串的结尾-我假设

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