1. 程式人生 > >正則表示式常見函式(爬蟲網頁匹配)

正則表示式常見函式(爬蟲網頁匹配)

一、區域性匹配(只匹配一個結果)

1.re.match()函式  :從源字元的串的開頭進行匹配

2.re.search()函式 :在全文中進行檢索並匹配

從例子中看區別:

import re
#string ="apythonhellomypythonisouorpythonend"
string = "hellomypythonispythonourpythonend"
pattern=".python."
result =re.match(pattern,string)
result2 = re.search(pattern,string)
print (result)
print (result2)

執行結果:


二、全域性匹配(找出所有的匹配結果)

1)使用re.compile()對正則式進行預編譯

2)編譯後,使用findall()根據正則表示式從源字串中獎匹配的結果全部找出

import re
#string ="apythonhellomypythonisouorpythonend"
string = "hellomypythonispythonourpythonend"
pattern=".python."
su = re.compile(pattern)
result = su.findall(string)
#合併寫法
result2 = re.compile(pattern).findall(string)
print (result2)

執行結果:


三、替換

import re
string = "hellomypythonispythonourpythonend"
pattern=".python."
su = re.sub(pattern,"php",string)
su1 = re.sub(pattern,"php",string,2)
print (su)
print (su1)

執行結果:


四、常見例項,查詢網址

import re
pattern = "[a-zA-Z]+://[^/s]*[.com|.cn]"    #注意+的前後不要有空格,不然結果為None
string ="<a herf = 'http://www.baidu.com'>百度首頁</a>"
result = re.search(pattern,string)
print (result)

result: