優勢:簡潔 一行勝千言
用於對字符串的匹配
在文本處理中十分常用
正則表達式的使用表達文本類型的特征(病毒,入侵檢測)同時查找或替換一組字符串匹配字符串的局部和全部
首先將符合正則表達式語法的字符串轉化成正則表達式 特征
p = re.compile(regx)
操作符 | 說明 | 實例 |
. | 表示任何單個字符 | |
[ ] | 字符集,對單個字符給出取值范圍 | [abc]表示a、b、c,[a-z]表示所有的小寫字母 |
[^] | [^abc]表示非a或b或c的單個字符 | |
* | 前一個字符0次或無限次擴展 | abc*表示ab,abc,abcc,abccc等 |
+ | 前一個字符1次或無限次擴展 | abc+表示abc,abcc,abccc等 |
? | 前一個字符0次或1次擴展 | abc?表示ab,abc |
| | 左右表達式任意一個 | abc|def表示abc或def |
{m} | 擴展前一個字符m次 | ab{2}c表示abbc |
{m,n} | 擴展前一個字符m至n次(含n) | ab{1,2}c表示abc,abbc |
^ | 匹配字符串開頭 | ^abc表示abc在一個字符串的開頭 |
$ | 匹配字符串結尾 | abc$表示abc在一個字符串的結尾 |
() | 分組標識,內部只能使用|操作符 | (abc)表示abc,(abc|def)表示abc,def |
\d | 數字,等價於[0-9] | |
\w | 單詞字符等價於[A-Za-z0-9_] |
^[A-Za-z]+$ | 由26個字母組成的字符串 |
^[A-Za-z0-9]+$ | 由26個字母和數字組成的字符串 |
^-?\d+$ | 數據形式的字符串 |
^[0-9]*[1-9][0-9]*$ | 正整數形式的字符串 |
[1-9]\d{5} | 中國境內的郵政編碼 |
[\u4e00-\u9fa5] | 匹配中文字符 |
\d{3}-\d{8}|\d{4}-\d{7} | 國內電話號碼 |
(([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]).){3}([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]) | IP地址 |
import re
re庫采用raw string類型表示正則表達式,表示為
r'text'
如: r'[1-9]\d{5}
'
r'\d{3}-\d{8}|\d{4}-\d{7}'
raw string是不包括對轉義字符再次轉義的字符串,建議使用raw string
Re庫的主要功能函數
函數 | 說明 |
re.search(pattern,string,flags=0) | 在一個字符串中匹配正則表達式的第一個位置,返回match對象 |
re.match(pattern,string,flags=0) | 從一個字符串的開始位置起匹配正則表達式,返回match對象 |
re.findall(pattern,string,flags=0) | 搜索字符串,以列表類型返回全部能匹配的子串 |
re.split(pattern,string,maxsplit=0,flags=0) | 將一個字符串按照正則表達式匹配結果進行侵害,返回列表類型, maxsplit表示最大分割數,剩余部分作為最后一個元素輸出 |
re.finditer(pattern,string,flags=0) | 搜索字符串,返回一個匹配結果的迭代類型,每個迭代元素是match對象 |
re.sub(pattern,repl,string,count=0,flags = 0) | 在一個字符串中替換所有匹配正則表達式的子串,返回替換后的字符串,repl為替換匹配字符串的字符串,count為最大替換次數 |
re.compile(pattern,flags = 0) | 將正則表達式的字符串形式編譯所正則表達式對象 |
flags | 說明 |
re.I re.IGONRECASE | 忽略正則表達式的大小寫,[A-Z]能匹配小寫字符 |
re.M re.MULTILINE | 正則表達式的中的^操作符能夠將給定字符串的每行當作匹配開始位置 |
re.S re.DOTALL | 正則表達式的中的.操作符能夠匹配所有字符,默認匹配除換行外的所有字符 |
函數式用法,一次性操作
rst = re.search(r'[1-9]\d{5}','BIT 10081')
面向對象用法,編譯后多次操作
pat = re.compile(r' [1-9]\d{5}')rst = pat.search('BIT 10081')
Match對象 是一次匹配的結果,包含匹配的很多信息
Match對象的屬性
屬性 | 說明 |
.string | 待匹配的文本 |
.re | 匹配進使用pattern對象(正則表達式) |
.pos | 正則表達式搜索文本的開始位置 |
.endpos | 正則表達式搜索文本的結束位置 |
方法 | 說明 |
.group(0) | 獲得匹配的字符串 |
.start() | 匹配字符串在原始字符串的開始位置 |
.end() | 匹配字符串在原始字符串的結束位置 |
.span() | 返回(.start(),.end()) |
貪婪匹配:re庫默認采用貪婪匹配,即輸出匹配最長的子串
如:

最小匹配:如何輸出最短的子串
操作符 | 說明 |
*? | 前一個字符0次或無限次擴展,最小匹配 |
+? | 前一個字符1次或無限次擴展,最小匹配 |
?? | 前一個字符0次或1次擴展,最小匹配 |
{m,n}? | 前一個字符m至n次(含n),最小匹配 |
實例1:淘寶比價爬蟲
#CrowTaobaoPrice.py
import requests
import re
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def parsePage(ilt, html):
try:
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price , title])
except:
print("")
def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序號", "價格", "商品名稱"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g[0], g[1]))
def main():
goods = '書包'
depth = 3
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList, html)
except:
continue
printGoodsList(infoList)
main()
實例2 股票數據爬蟲
#CrawBaiduStocksB.py
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url, code="utf-8"):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
return r.text
except:
return ""
def getStockList(lst, stockURL):
html = getHTMLText(stockURL, "GB2312")
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html=="":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名稱': name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath, 'a', encoding='utf-8') as f:
f.write( str(infoDict) + '\n' )
count = count + 1
print("\r當前進度: {:.2f}%".format(count*100/len(lst)),end="")
except:
count = count + 1
print("\r當前進度: {:.2f}%".format(count*100/len(lst)),end="")
continue
def main():
stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:/BaiduStockInfo.txt'
slist=[]
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()