爬蟲入門3(正則表達式)

1.常用符號
. 匹配任意單個字符,如 a.b 為a“任意某個字符”b acb adb
\ 轉(zhuǎn)義字符
[...]為字符集,相當于在括號中任選一個

2.預(yù)定義字符集
\d 匹配任意數(shù)字,等價于 [0-9]
\D 匹配任意非數(shù)字,等價于[^0-9]
\s 匹配任意空白字符,等價于 [\t\n\r\f\v]
\S 匹配任意非空字符,等價于[^\t\n\r\f\v]
\w 匹配包括下劃線的任何單詞字符。等價于'[A-Za-z0-9_]'
\W 匹配任何非單詞字符。等價于 '[^A-Za-z0-9_]'

3.數(shù)量詞
“*” 匹配前一個字符0或無限次
“+” 1或無限次
? 0或1次
{m} m次
{m,n} m到n次
例如ab?c 則為匹配ac abc

4.邊界匹配
^ 匹配字符串開頭
$ 匹配字符串結(jié)尾
\A 僅匹配字符串開頭
\Z 僅匹配字符串結(jié)尾

python中常用的(.?), () 表示括號的內(nèi)容作為返回結(jié)果,返回的為列表
“.
?”是非貪心算法,匹配任意的字符,例如:“xxIxxhatexxphysicsxx”
可以通過'xx(.*?)xx'匹配符合這種規(guī)則的字符串

re模塊及其方法
1.compile(pattern, flags=0) compile 編譯 pattern 模式 基本上不用
給定一個正則表達式 pattern,指定使用的模式 flags 默認為0 即不使用任何模式,然后會返回一個SRE_Pattern
'''
regex = re.compile(".+")
print regex
output> <_sre.SRE_Pattern object at 0x00000000026BB0B8>
'''
這個對象可以調(diào)用其他函數(shù)來完成匹配,一般來說推薦使用 compile 函數(shù)預(yù)編譯出一個正則模式之后再去使用,這樣在后面的代碼中可以很方便的復(fù)用它,當然大部分函數(shù)也可以不用 compile 直接使用,具體見 findall 函數(shù)

2.findall(pattern, string, flags=0)

參數(shù) pattern 為正則表達式, string 為待操作字符串, flags 為所用模式,函數(shù)作用為在待操作字符串中尋找所有匹配正則表達式的字串,返回一個列表,如果沒有匹配到任何子串,返回一個空列表。
'''
s = '''first line
second line
third line'''

compile 預(yù)編譯后使用 findall
regex = re.compile("\w+")
print regex.findall(s)
output> ['first', 'line', 'second', 'line', 'third', 'line']

不使用 compile 直接使用 findall
print re.findall("\w+", s)
output> ['first', 'line', 'second', 'line', 'third', 'line']
'''

3.match(pattern, string, flags=0)

使用指定正則去待操作字符串中尋找可以匹配的子串, 返回匹配上的第一個字串,并且不再繼續(xù)找,需要注意的是 match 函數(shù)是從字符串開始處開始查找的,如果開始處不匹配,則不再繼續(xù)尋找,返回值為 一個 SRE_Match 對象,找不到時返回 None
'''
s = '''first line
second line
third line'''

compile實例用法:
regex = re.compile("\w+")
m = regex.match(s)
print m
output> <_sre.SRE_Match object at 0x0000000002BCA8B8>
print m.group()
output> first

s 的開頭是 "f", 但正則中限制了開始為 i 所以找不到
regex = re.compile("^i\w+")
print regex.match(s)
output> None
'''

4.search(pattern, string, flags=0)

函數(shù)類似于 match,不同之處在于不限制正則表達式的開始匹配位置
s = '''first line
second line
third line'''

需要從開始處匹配 所以匹配不到

print re.match('i\w+', s)
output> None

沒有限制起始匹配位置(所以一般用search()方法)

print re.search('i\w+', s)
output> <_sre.SRE_Match object at 0x0000000002C6A920>

print re.search('i\w+', s).group()
output> irst

5.sub(pattern, repl, string, count=0, flags=0)

替換函數(shù),將正則表達式 pattern 匹配到的字符串替換為 repl 指定的字符串, 參數(shù) count 用于指定最大替換次數(shù)

'''
s = "the sum of 7 and 9 is [7+9]."

基本用法 將目標替換為固定字符串
print re.sub('[7+9]', '16', s)
output> the sum of 7 and 9 is 16.

高級用法 1 使用前面匹配的到的內(nèi)容 \1 代表 pattern 中捕獲到的第一個分組的內(nèi)容
print re.sub('[(7)+(9)]', r'\2\1', s)
output> the sum of 7 and 9 is 97.

高級用法 2 使用函數(shù)型 repl 參數(shù), 處理匹配到的 SRE_Match 對象
def replacement(m):
p_str = m.group()
if p_str == '7':
return '77'
if p_str == '9':
return '99'
return ''
print re.sub('\d', replacement, s)
output> the sum of 77 and 99 is [77+99].

高級用法 3 使用函數(shù)型 repl 參數(shù), 處理匹配到的 SRE_Match 對象 增加作用域 自動計算
scope = {}
example_string_1 = "the sum of 7 and 9 is [7+9]."
example_string_2 = "[name = 'Mr.Gumby']Hello,[name]"

def replacement(m):
code = m.group(1)
st = ''
try:
st = str(eval(code, scope))
except SyntaxError:
exec code in scope
return st

解析: code='7+9'
str(eval(code, scope))='16'
print re.sub('[(.+?)]', replacement, example_string_1)
output> the sum of 7 and 9 is 16.

兩次替換
解析1: code="name = 'Mr.Gumby'"
eval(code)
raise SyntaxError
exec code in scope
在命名空間 scope 中將 "Mr.Gumby" 賦給了變量 name

解析2: code="name"
eval(name) 返回變量 name 的值 Mr.Gumby
print re.sub('[(.+?)]', replacement, example_string_2)
output> Hello,Mr.Gumby
'''

其中最常用最easy的就是findall()用法,例如

'''
import lxml
import requests
from bs4 import BeautifulSoup
import time
import re

headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'
}
url="http://bj.xiaozhu.com/"
web_data=requests.get(url,headers=headers)
prices=re.findall('<span class="result_price">¥<i>(.*?)</i></span>',web_data.text)
print(prices)
'''


找findall內(nèi)容的時候在右鍵查看網(wǎng)頁源代碼里面找,如上圖。

re模塊修飾符
修飾符 描述
re.I 使匹配對大小寫不敏感
re.L 做本地化識別(locale-aware)匹配
re.M 多行匹配,影響 ^ 和 $
re.S 使 . 匹配包括換行在內(nèi)的所有字符
re.U 根據(jù)Unicode字符集解析字符。這個標志影響 \w, \W, \b, \B.
re.X 該標志通過給予你更靈活的格式以便你將正則表達式寫得更易于理解。

最常用的就是re.S,它能夠?qū)崿F(xiàn)換行匹配,例如
'''
import re

s="""<div>爬蟲
</div>
"""
word=re.findall("<div>(.*?)</div>",s,re.S)
print(word)
print(word[0].strip())
'''
輸出如下:


image.png
?著作權(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)容

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