21-用句点字符匹配换行符
7.9.2 用句点字符匹配换行符
点-星将匹配换行符外的所有字符。传入 re.DOTALL
作为 re.compile()
的第二个参数,可以让句点字符匹配所有字符,包括换行符。
在交互式环境中输入以下代码:
>>> noNewlineRegex = re.compile('.*')
>>> noNewlineRegex.search('Serve the public trust.\nProtect the innocent.
\nUphold the law.').group()
'Serve the public trust.'
>>> newlineRegex = re.compile('.*', re.DOTALL)
>>> newlineRegex.search('Serve the public trust.\nProtect the innocent.
\nUphold the law.').group()
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
正则表达式 noNewlineRegex
在创建时没有向 re.compile()
传入 re.DOTALL
,它将匹配所有字符,直到出现第一个换行符。但是, newlineRegex
在创建时向 re.compile()
传入了 re.DOTALL
,它将匹配所有字符。 这就是为什么 newlineRegex. search()
匹配完整的字符串,包括其中的换行符。