python爬蟲的re庫(正則表示式匹配)
阿新 • • 發佈:2018-12-09
re庫是python中自帶的一個庫,不需要外部匯入。
它主要是支援正則表示式匹配。
下面來說一下其主要功能函式:
函式 | 說明 |
---|---|
re.search() | 在一個字串中搜索匹配正則表示式的第一個位置,返回match物件。 |
re.match() | 在一個字串的開始位置起匹配表示式,返回match物件 |
re.findall() | 搜尋字串,以列表型別返回全部能匹配的子串 |
re.split() | 將一個字串按照正則表示式的匹配結果進行分割,返回列表型別 |
re.finditer() | 搜尋字串,返回一個匹配結果的迭代型別,每個迭代元素是match物件 |
re.sub() | 在一個字串中替換所有匹配正則表示式的子串,返回替換後的字串 |
正則表示式使用標記:
常用標記 | 說明 |
---|---|
re.I re.IGNORECASE | 忽略正則表示式的大小寫 【A-Z】能夠匹配小寫字元 |
re.M re.MULITILINE | 正則表示式中的^操作符能夠將給定字串的每行當作匹配開始 |
re.S re.DOTALL | 正則表示式中的.操作符能夠匹配所有字元,預設匹配除換行外的所有字元 |
import re match = re.search(r'[1-9]\d{5}','BIT 100081') if match: print(match.group(0)) match2 = re.match(r'[1-9]\d{5}','100081 BIT') if match2: print(match2.group(0)) match3 = re.match(r'[1-9]\d{5}', 'BIT 100081') if match3: print(match3.group(0))
返回結果:
100081
100081
Process finished with exit code 0
第三個不返回 結果 因為他是從第一個開始匹配 很明顯第一個字母B和它的正則表示式不匹配,所以結果為空,那麼if判斷之後 將不會輸出。
import re
ls = re.findall(r'[1-9]\d{5}', 'BIT100081 FSABIT100085')
if ls:
print(ls)
ls = re.split(r'[1-9]\d{5}', 'BIT100081 FSABIT100085')
if ls:
print(ls)
ls = re.split(r'[1-9]\d{5}', 'BIT100081 FSABIT100085',maxsplit=1)
if ls:
print(ls)
for m in re.finditer(r'[1-9]\d{5}','BIT100081 FSABIT100085'):
if m:
print(m.group(0))
ls = re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 FSABIT100085')
print(ls)
輸出結果:
['100081', '100085']
['BIT', ' FSABIT', '']
['BIT', ' FSABIT100085']
100081
100085
BIT:zipcode FSABIT:zipcode
Process finished with exit code 0