pat = re.compile(r'(?ms)^---(.*)\Z')
(?ms)添加MULTILINE和DOTALL标志。
该MULTILINE标志^匹配行的开头(不仅仅是字符串的开头)。我们需要这个,因为它---出现在行的开头,但不一定是字符串的开头。
该DOTALL标志.匹配任何字符,包括换行符。我们需要这个,以便(.*)可以匹配多行。
\Z匹配字符串的结尾(而不是行尾)。
例如,
import re
text = '''\
Anything above this first set of hyphens should not be captured.
---
This is content. It should be captured.
Any sets of three hyphens beyond this point should be ignored.
'''
pat = re.compile(r'(?ms)^---(.*)\Z')
print(re.search(pat, text).group(1))
印刷
This is content. It should be captured.
Any sets of three hyphens beyond this point should be ignored.
请注意,当您使用方括号定义正则表达式字符类时,方括号[...]内的内容(通常,除了带连字符的范围以外a-z)解释为单个字符。它们不是模式。所以[---]与 没有什么不同[-]。实际上,[---]是字符的范围从-到-,包括在内。
字符类中的括号也被解释为文字括号,而不是分组分隔符。so[(---)]等价于[-()],包括连字符和左右括号的字符类。
因此,字符类[^(---)]+匹配除连字符或括号之外的任何字符:
In [23]: re.search('[^(---)]+', 'foo - bar').group()
Out[23]: 'foo '
In [24]: re.search('[^(---)]+', 'foo ( bar').group()
Out[24]: 'foo '
您可以看到这是怎么回事,以及为什么它对您的问题不起作用。