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
等连字符)解释为单个字符。他们不是模式。因此[---]
与[-]
没有区别。实际上,[---]
是从-
到-
(含)的字符范围。
字符类内的圆括号也被解释为文字圆括号,而不是分组分隔符。所以[(---)]
等于[-()]
,字符类包括连字符和左右括号。
因此字符类[^(---)]+
匹配比连字号或括号以外的任何字符:
In [23]: re.search('[^(---)]+', 'foo - bar').group()
Out[23]: 'foo '
In [24]: re.search('[^(---)]+', 'foo (bar').group()
Out[24]: 'foo '
你可以看到这是怎么回事,为什么它不适合您的问题的工作。
感谢您的帮助。这个解释很有帮助,更不用说它完美了。 – Battleroid