天天看點

Python RE子產品中search()和match()的差別

本文轉載自http://blog.csdn.net/cnmilan/article/details/9071999

match()函數隻檢測RE是不是在string的開始位置比對,

search()會掃描整個string查找比對;

也就是說match()隻有在0位置比對成功的話才有傳回,

如果不是開始位置比對成功的話,match()就傳回none。

例如:

print(re.match(‘super’, ‘superstition’).span())   會傳回(0, 5)

而print(re.match(‘super’, ‘insuperable’))   則傳回None

search()會掃描整個字元串并傳回第一個成功的比對

例如:print(re.search(‘super’, ‘superstition’).span())傳回(0, 5)

print(re.search(‘super’, ‘insuperable’).span())傳回(2, 7)