這個(gè)問題一般出現(xiàn)在希望使用句點(diǎn)(.)來匹配任意字符,但是忘記了句點(diǎn)并不能匹配換行符時(shí):
import re
comment = re.compile(r'/\*(.*?)\*/') # 匹配C的注釋
text1 = '/* this is a comment */'
text2 = """/*this is a
multiline comment */"""
comment.findall(text1)
Out[4]: [' this is a comment ']
comment.findall(text2) # 由于text2文本換行了咱扣,沒匹配到
Out[5]: []
解決方法1:添加對換行符的支持止潘,(?:.|\n)
指定了一個(gè)非捕獲組(即砌烁,這個(gè)組只做匹配但不捕獲結(jié)果,也不會(huì)分配組號)
comment = re.compile(r'\*((?:.|\n)*?)\*/')
comment.findall(text2)
Out[7]: ['this is a \n multiline comment ']
解決方法2:re.compile()函數(shù)可接受一個(gè)有用的標(biāo)記--re.DOTALL贺待。這使得正則表達(dá)式中的句點(diǎn)(.)可以匹配所有的字符,也包括換行符
comment = re.compile(r'/\*(.*?)\*/', flags=re.DOTALL)
comment.findall(text2)
Out[10]: ['this is a \n multiline comment ']