点-星将匹配除换行外的所有字符。通过传入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()调用匹配完整的字符串,包括其中的换行字符。
网友评论