利用正则表达式去匹配一大块的文本,你须要超过多行去匹配。
这个问题很范例的涌如今当你用点 (.) 去匹配任意字符的时候,忘却了点 (.) 不能匹配换行符的事实。比如:
my_text = """ The sky is blue, the sea is green. You are the everlasting sun in my heart. """my_text_one = ' The sky is blue, the sea is green. 'patter_compiled = re.compile(r'\(.)\')print(patter_compiled.findall(my_text_one))# [' The sky is blue, the sea is green. ']print(patter_compiled.findall(my_text))# []
为了改动这个问题,你可以修正模式字符串,增加对换行的支持。比如:

my_text = """ The sky is blue, the sea is green. You are the everlasting sun in my heart. """patter_compiled_mu = re.compile(r'\((?:.|\n))\')print(patter_compiled_mu.findall(my_text))# [' The sky is blue, the sea is green.\n You are the everlasting sun in my heart. ']
在这个模式中, (?:.|\n) 指定了一个非捕获组 (也便是它定义了一个仅仅用来做匹配,而不能通过单独捕获或者编号的组)
re.compile() 函数接管一个标志参数叫 re.DOTALL ,在这里非常有用。它可以让正则表达式中的点 (.) 匹配包括换行符在内的任意字符。比如:
patter_compiled_dot = re.compile(r'\(.)\', flags=re.DOTALL)print(patter_compiled_dot.findall(my_text))# [' The sky is blue, the sea is green.\n You are the everlasting sun in my heart. ']
对付大略的情形利用 re.DOTALL 标记参数事情的很好,但是如果模式非常繁芜或者是为告终构字符串令牌而将多个模式合并起来 ,这时候利用这个标记参数就可能涌现一些问题。如果让你选择的话,最好还是定义自己的正则表达式模式,这样它可以在不须要额外的标记参数下也能事情的很好。
官方对付正则表达式中的点(.)的阐明:
.(Dot.)
In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.
在默认模式下,它匹配除换行符以外的任何字符。 如果指定了DOTALL标志,则它匹配包括换行符在内的任何字符。