python 多行匹配
python多行匹配
r = re.compile("需要的正则表达式", re.M)
匹配到需要的字符,可以获取红括号内的数字
r = re.compile("r([0-9]{5,})")
举个例子: 需要获取20462和24729连个数字
import re
data = """
r24062 line1
hello word !!!!
r24729 line2
revision:24181
"""
r = re.compile("^r([0-9]{5,})", re.M)
nums = r.findall(data)
print nums
---------------------
output:["24062", "24729"]
如果你要多行匹配,那么加上re.S和re.M标志
re.S:.将会匹配换行符,默认.逗号不会匹配换行符
>>> re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b")
[]
>>> re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b",re.S)
[('23','34')]
>>>
[]
>>> re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b",re.S)
[('23','34')]
>>>
re.M:^$标志将会匹配每一行,默认^只会匹配符合正则的第一行;默认$只会匹配符合正则的末行
>>> re.findall(r"^a(\d+)b","a23b\na34b")
['23']
>>> re.findall(r"^a(\d+)b","a23b\na34b",re.M)
['23','34']
['23']
>>> re.findall(r"^a(\d+)b","a23b\na34b",re.M)
['23','34']
但是,如果没有^标志,
>>> re.findall(r"a(\d+)b","a23b\na34b")
['23','43']
['23','43']
可见,是无需re.M