re.S

re.S:表示将作用扩展到整个字符串,包括 '\n',将 '\n' 变成普通字符整合到字符串中

案例

import re
a = '''asdfhellopass:
    123
    worldaf
    '''
b = re.findall('hello(.*?)world',a)
c = re.findall('hello(.*?)world',a,re.S)
print 'b is ' , b
print 'c is ' , c

运行结果如下:

b is  []
c is  ['pass:\n\t123\n\t']

分析

hello(.*?)world表示匹配hello和word之间的所有非'\n'的字符
当不使用re.S时,它一行一行去匹配(以'\n'来区分每一行),b没有使用re.S则先匹配字符串'asdfhellopass:',然后在重新匹配字符串'123'直至结束,所以没有匹配到符合的语句
当使用re.S时,它匹配的字符串为'asdfhellopass:\n\t123\n\twordaf'所以为如上结果
这时候你可能感到疑问 . 不是匹配除'\n'外的所有单字符吗?为什么结果中还有'\n',因为这时候'\n'已经被re.S变成普通的字符,不再是换行符

猜你喜欢

转载自www.cnblogs.com/Wuser/p/12551448.html
今日推荐