正常的情况下,正则表达式里的句号(.)是匹配任何除换行符之外的字符。但是有时你也想要求它连换行符也匹配,这时怎么办呢?其实不用急,可以使用DOTALL标志,就可以让它匹配所有字符,不再排除换行符了。如下例子:
深入浅出Numpy
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = 'This is some text -- with punctuation.\nA second line.'
pattern = r'.+'
no_newlines = re.compile(pattern)
dotall = re.compile(pattern, re.DOTALL)
print('Text:\n {!r}'.format(text))
print('Pattern:\n {}'.format(pattern))
print('No newlines :')
for match in no_newlines.findall(text):
print(' {!r}'.format(match))
print('Dotall :')
for match in dotall.findall(text):
print(' {!r}'.format(match))
结果输出如下:
Text:
'This is some text -- with punctuation.\nA second line.'
Pattern:
.+
No newlines :
'This is some text -- with punctuation.'
'A second line.'
Dotall :
'This is some text -- with punctuation.\nA second line.'