python 2.6.8
s= '''
foo
bar
baz
'''
>>>re.findall(r'^\S*',s,re.MULTILINE)
['', 'foo', 'bar', 'baz', '']
>>>ptrn = re.compile(r'^\S*',re.MULTILINE)
>>>ptrn.findall(s)
['', 'foo', 'bar', 'baz', '']
>>>ptrn.findall(s,re.MULTILINE)
['baz', '']
为什么在findall中使用MULTILINE标志有什么区别?
答案 0 :(得分:22)
在regex对象上调用findall()
方法时,第二个参数不是flags
参数(因为在编译正则表达式时已经使用过),而是pos
参数,告诉正则表达式引擎在字符串中的哪一点开始匹配。
re.MULTILINE
只是一个整数(恰好是8
)。
请参阅the docs。
答案 1 :(得分:7)
因为编译对象findall
的{{1}}方法不采用MULTILINE参数。它需要一个ptrn
参数。
见这里:http://docs.python.org/library/re.html#re.RegexObject.findall
MULTILINE说明符仅在您致电position
时使用。生成的re.compile()
对象已“知道”它是ptrn
。