Python中的正則表達式

前言

正則表達式作為一種字符串匹配邏輯,在此不做贅述。本文的重點,并不是正則表達式,而是在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'


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 為什么要使用正則表達式 在軟件開發(fā)過程中,經(jīng)常涉及到大量的關(guān)鍵字等各種字符串的操作,使用正則表達式能很大簡化開發(fā)的...
    偉大的洪立閱讀 405評論 0 0
  • re模塊的高級應(yīng)用 search 執(zhí)行正則表達式搜索并且在搜索結(jié)束后返回所匹配到的串,只返回第一次匹配到的結(jié)果求出...
    偉大的洪立閱讀 333評論 0 0
  • 正則表達式使用步驟 1. 用import re導(dǎo)入正則表達式 2. 用re.compile()函數(shù)創(chuàng)建一個Rege...
    LorryZ閱讀 464評論 0 1
  • 非教程——僅供參考以下內(nèi)容只說明在Python中如何使用正則表達式,對正則表達式本身不再說明,如果想了解正則表達式...
    Jiafu閱讀 316評論 0 0
  • 愛情,是什么,就是一種奮不顧身,去保護喜歡的人,愛情分為幾類?第一類是兩個人,真心相愛,第二個,那就是,兩個女的同...
    美噠噠的閱讀 313評論 0 0

友情鏈接更多精彩內(nèi)容