前言
正則表達式作為一種字符串匹配邏輯,在此不做贅述。本文的重點,并不是正則表達式,而是在Python中使用正則表達式。
Re模塊
Python 自帶了re模塊,它提供了對正則表達式的支持。主要用到的方法列舉如下
#返回pattern對象
re.compile(string[,flag])
#以下為匹配所用函數(shù)
re.match(pattern, string[, flags])
re.search(pattern, string[, flags])
re.split(pattern, string[, maxsplit])
re.findall(pattern, string[, flags])
re.finditer(pattern, string[, flags])
re.sub(pattern, repl, string[, count])
re.subn(pattern, repl, string[, count])
舉個例子
# -*- coding: utf-8 -*-
#導(dǎo)入re模塊
import re
# 將正則表達式編譯成Pattern對象,注意hello前面的r的意思是“原生字符串”
pattern = re.compile(r'hello')
# 使用re.match匹配文本,獲得匹配結(jié)果,無法匹配時將返回None
result1 = re.match(pattern,'hello')
result2 = re.match(pattern,'helloo CQC!')
result3 = re.match(pattern,'helo CQC!')
result4 = re.match(pattern,'hello CQC!')
其中,只有result3會為false。
舉個大例子
要求
獲取糗事百科首頁的所有jpg圖片的url
code
import urllib2
import re
# create header
page = 1
url = 'http://www.qiushibaike.com/hot/page/' + str(page)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
# get original page
request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request).read()
# complie image and jpg tag
pattern = re.compile(r'<img\ssrc="http://[^\s]*.jpg')
# find all out
result = re.findall(pattern, response)
# print result
if result:
for r in result:
index = len(r)
print r[12:index]
else:
print 'match none'