- re模塊的常見(jiàn)方法
- 原始字符串r
- 匹配中文
re模塊的常見(jiàn)方法
-
re.match()從頭找一個(gè) -
re.search()找一個(gè) -
re.findal()找所有
返回一個(gè)列表,沒(méi)有就是空表
ret = re.findall("\d","chuan1zhi2")
>>['1', '2']
-
re.sub()替換
re.sub("\d","_","wu1xuan2")
>>wu_xuan_
-
re.compile()編譯
返回一個(gè)模型P,具有和re一樣的方法,但是傳遞的參數(shù)不同
匹配模式需要傳到compile中
p = re.compile("\d",re.S)
p.findall("chuan1zhi2")
python中原始字符串r的用法
原始字符串(raw string):保持原先字符串中所有的字符
如:“\n”的原始字符串就是“\\n”
len("\n")
>>1
len(r"\n")
>>2
- 正則中使用原始字符串
r忽略轉(zhuǎn)義符號(hào)帶來(lái)的影響
匹配中文
中文 unicode 編碼范圍:[u4e00-u9fa5](不包含中文標(biāo)點(diǎn))
注意:漢字和正則表達(dá)式都需要是unicode字符操作
【練習(xí)】提取中文
# coding:utf-8
import re
title="<p>Look out your window and I`ll be gone</p> <p>看向你的窗外我早已離開(kāi)</p> <p>You`re the reason I`m traveling on</p> <p>因?yàn)槟阄也潘奶幤?lt;/p> "
p = re.findall(r"[\u4E00-\u9FA5]+",title)
print(p)
>>['看向你的窗外我早已離開(kāi)', '因?yàn)槟阄也潘奶幤?]