Python正則表達式re模塊詳解(建議收藏!)
前言
正則表達式是對字符串提取的一套規(guī)則,我們把這個規(guī)則用正則里面的特定語法表達出來,去匹配滿足這個規(guī)則的字符串。正則表達式具有通用型,不僅python里面可以用,其他的語言也一樣適用。
python中re模塊提供了正則表達式的功能,常用的有四個方法(match、search、findall)都可以用于匹配字符串
match
匹配字符串
re.match()必須從字符串開頭匹配!match方法嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。主要參數(shù)如下:
re.match(pattern, string) # pattern 匹配的正則表達式 # string 要匹配的字符串
例子
import re a = re.match('test','testasdtest') print(a) #返回一個匹配對象 print(a.group()) #返回test,獲取不到則報錯 print(a.span()) #返回匹配結(jié)果的位置,左閉右開區(qū)間 print(re.match('test','atestasdtest')) #返回None
從例子中我們可以看出,re.match()方法返回一個匹配的對象,而不是匹配的內(nèi)容。如果需要返回內(nèi)容則需要調(diào)用group()。通過調(diào)用span()可以獲得匹配結(jié)果的位置。而如果從起始位置開始沒有匹配成功,即便其他部分包含需要匹配的內(nèi)容,re.match()也會返回None。
單字符匹配
以下字符,都匹配單個字符數(shù)據(jù)。且開頭(從字符串0位置開始)沒匹配到,即使字符串其他部分包含需要匹配的內(nèi)容,.match也會返回none
. 匹配任意一個字符
使用幾個點號就代表幾個字符
import re a = re.match('..','testasdtest') print(a.group()) #輸出te b = re.match('ab.','testasdtest') print(b) #返回none,因為表達式是以固定的ab開頭然后跟上通配符. 所以必須要先匹配上ab才會往后進行匹配
\d 匹配數(shù)字
一個\d代表一個數(shù)字。開頭沒匹配到,即使字符串其他部分包含需要匹配的內(nèi)容,.match也會返回none
import re a = re.match('\d\d','23es12testasdtest') print(a) b = re.match('\d\d\d','23es12testasdtest') print(b) #要求匹配三個數(shù)字,匹配不到返回none c = re.match('\d','es12testasdtest') print(c) #起始位置沒有匹配成功,一樣返回none
\D 匹配非數(shù)字
開頭沒匹配到,即使字符串其他部分包含需要匹配的內(nèi)容,.match也會返回none
import re a = re.match('\D','23es12testasdtest') print(a) #開頭為數(shù)字所以返回none b = re.match('\D\D','*es12testasdtest') print(b) #返回*e
\s 匹配特殊字符,如空白,空格,tab等
import re print(re.match('\s',' 23es 12testasdtest')) #匹配空格 print(re.match('\s',' 23es 12testasdtest')) #匹配tab print(re.match('\s','\r23es 12testasdtest')) #匹配\r換行 print(re.match('\s','23es 12testasdtest')) #返回none
\S 匹配非空白
import re print(re.match('\S',' 23es 12testasdtest')) #返回none print(re.match('\S','\r23es 12testasdtest')) #none print(re.match('\S','23es 12testasdtest'))
\w 匹配單詞、字符,如大小寫字母,數(shù)字,_ 下劃線
import re print(re.match('\w','23es 12testasdtest')) #返回none print(re.match('\w\w\w','aA_3es 12testasdtest')) #返回none print(re.match('\w\w\w','\n12testasdtest')) #返回none
\W 匹配非單詞字符
import re print(re.match('\W','23es 12testasdtest')) #返回none print(re.match('\W',' 23es 12testasdtest')) #匹配空格
[ ] 匹配[ ]中列舉的字符
只允許出現(xiàn)[ ]中列舉的字符
import re print(re.match('12[234]','232s12testasdtest')) #因為開頭的12沒匹配上,所以直接返回none print(re.match('12[234]','1232s12testasdtest')) #返回123
[^2345] 不匹配2345中的任意一個
import re print(re.match('12[^234]','232s12testasdtest')) #因為開頭的12沒匹配上,所以直接返回none print(re.match('12[^234]','1232s12testasdtest')) #返回none print(re.match('12[^234]','1252s12testasdtest')) #返回125
[a-z3-5] 匹配a-z或者3-5中的字符
import re print(re.match('12[1-3a-c]','1232b12testasdtest')) #123 print(re.match('12[1-3a-c]','12b2b12testasdtest')) #12b print(re.match('12[1-3a-c]','12s2b12testasdtest')) #返回none
表示數(shù)量
像上面寫的那些都是匹配單個字符,如果我們要匹配多個字符的話,只能重復(fù)寫匹配符。這樣顯然是不人性化的,所以我們還需要學(xué)習(xí)表達數(shù)量的字符
* 出現(xiàn)0次或無數(shù)次
import re a = re.match('..','testasdtest') print(a.group()) #輸出te a = re.match('.*','testasdtest') print(a.group()) #全部輸出
import re print(re.match('a*','aatestasdtest')) #匹配跟隨在字母a后面的所有a字符 print(re.match('\d*','23aatestasdtest')) #匹配前面為數(shù)字的字符 print(re.match('a\d*','ad23aatestasdtest')) #輸出a, 因為*也可以代表0次
+ 至少出現(xiàn)一次
import re print(re.match('a+','aaatestasdtest')) #匹配前面為字母a的字符,且a至少有1一個 print(re.match('a+','atestasdtest')) #a print(re.match('a+','caaatestasdtest')) #none
? 1次或則0次
import re print(re.match('a?','abatestasdtest')) #匹配a出現(xiàn)0次或者1次數(shù) print(re.match('a?','batestasdtest')) #輸出空,因為a可以為0次 print(re.match('a?','aaatestasdtest')) #a出現(xiàn)0次或者1次,輸出1個a
{m}指定出現(xiàn)m次
import re print(re.match('to{3}','toooooabatestasdtest')) #匹配t以及跟隨在后面的三個ooo print(re.match('to{3}','tooabatestasdtest')) #只有兩個0,返回none
{m,} 至少出現(xiàn)m次
import re print(re.match('to{3}','toooooabatestasdtest')) #匹配t以及跟隨在后面的三個ooo print(re.match('to{3}','tooabatestasdtest')) #只有兩個0,返回none
{m,n} 指定從m-n次的范圍
import re print(re.match('to{3,4}','toooabatestasdtest')) #剛好有三個ooo,成功匹配 print(re.match('to{3,4}','tooabatestasdtest')) #只有兩個o,返回none print(re.match('to{3,4}','toooooabatestasdtest')) #提取最多四個o
匹配邊界
$ 匹配結(jié)尾字符
定義整個字符串必須以指定字符串結(jié)尾
import re print(re.match('.*d$','2testaabcd')) #字符串必須以d結(jié)尾 print(re.match('.*c','2testaabcd')) #字符串不是以c結(jié)尾,返回none
^ 匹配開頭字符
定義整個字符串必須以指定字符開頭
import re print(re.match('^2','2stoooabatestas')) #規(guī)定必須以2開頭,否則none print(re.match('^2s','2stoooabatestas')) #必須以2s開頭
\b 匹配一個單詞的邊界
\b:表示字母數(shù)字與非字母數(shù)字的邊界,非字母數(shù)字與字母數(shù)字的邊界。即下面ve的右邊不能有字母和數(shù)字
import re print(re.match(r'.*ve\b','ve.2testaabcd')) #因為在python中\(zhòng)代表轉(zhuǎn)義,所以前面加上r消除轉(zhuǎn)義 print(re.match(r'.*ve\b','ve2testaabcd'))
\B 匹配非單詞邊界
import re print(re.match(r'.*ve\B','2testaavebcdve')) #ve的右邊需要有字母或者數(shù)字 print(re.match(r'.*ve\B','2testaave3bcdve'))
匹配分組
| 匹配左右任意一個表達式
只要|兩邊任意一個表達式符合要求就行
import re print(re.match(r'\d[1-9]|\D[a-z]','2233')) #匹配|兩邊任意一個表達式 print(re.match(r'\d[1-9]|\D[a-z]','as'))
(ab) 將括號中字符作為一個分組
()中的內(nèi)容會作為一個元組字符裝在元組中
import re a = re.match(r'<h1>(.*)<h1>','<h1>你好啊<h1>') print(a.group()) #輸出匹配的字符 print(a.groups()) #會將()中的內(nèi)容會作為一個元組字符裝在元組中 print('`````````````') b = re.match(r'<h1>(.*)(<h1>)','<h1>你好啊<h1>') print(b.groups()) #有兩括號就分為兩個元組元素 print(b.group(0)) #group中默認(rèn)是0 print(b.group(1)) #你好啊 print(b.group(2)) #h1
search
和match差不多用法,從字符串中進行搜索
import re print(re.match(r'\d\d','123test123test')) print(re.search(r'\d\d','123test123test'))
findall
從字面意思上就可以看到,findall是尋找所有能匹配到的字符,并以列表的方式返回
import re print(re.match(r'\d\d','123test123test')) print(re.search(r'\d\d','123test123test'))
re.s
findall中另外一個屬性re.S
在字符串a(chǎn)中,包含換行符\n,在這種情況下
- 如果不使用re.S參數(shù),則只在每一行內(nèi)進行匹配,如果一行沒有,就換下一行重新開始。
- 而使用re.S參數(shù)以后,正則表達式會將這個字符串作為一個整體,在整體中進行匹配。
如下要尋找test.*123的數(shù)據(jù),因為test和123在不同的行,如果沒加re.s的話,他會在每一個進行匹配查找而不是將字符串作為一個整體進行查找
import re a = """aaatestaa aaaa123""" print(re.findall(r'test.*123',a)) print(re.findall(r'test.*123',a,re.S))
sub
查找字符串中所有相匹配的數(shù)據(jù)進行替換
sub(要替換的數(shù)據(jù),替換成什么,要替換的數(shù)據(jù)所在的數(shù)據(jù))
import re print(re.sub('php','python','php是世界上最好的語言——php')) #輸出 "python是世界上最好的語言——python"
split
對字符串進行分割,并返回一個列表
import re s = "itcase,java:php-php3;html" print(re.split(r",",s)) #以,號進行分割 print(re.split(r",|:|-|;",s)) #以,或者:或者-或者;進行分割 print(re.split(r",|:|-|%",s)) #找不到的分隔符就忽略
貪婪與非貪婪
python里的數(shù)量詞默認(rèn)是貪婪的,總是嘗試盡可能的匹配更多的字符。python中使用?號關(guān)閉貪婪模式
如
import re print(re.match(r"aa\d+","aa2323")) #會盡可能多的去匹配\d print(re.match(r"aa\d+?","aa2323")) #盡可能少的去匹配\d
import re s = "this is a number 234-235-22-423" # 1.貪婪模式 resule = re.match(r"(.+)(\d+-\d+-\d+-\d)",s) #我們本想數(shù)字和字母拆解成兩個分組 print(resule.groups()) #('this is a number 23', '4-235-22-4')但我們發(fā)現(xiàn)輸出的結(jié)果中23的數(shù)字竟然被弄到前面去了 #因為+它會盡可能多的進行匹配,\d,只需要一個4就能滿足,所以前面就盡可能多的匹配 # 2.關(guān)閉貪婪模式 #在數(shù)量詞后面加上 ?,進入非貪婪模式,盡可能少的進行匹配 result = re.match(r"(.+?)(\d+-\d+-\d+-\d)",s) print(result.groups()) #('this is a number ', '234-235-22-4')
案例
匹配手機號
要求,手機號為11位,必須以1開頭,且第二個數(shù)字為35678其種一個
import re result = re.match(r'1[35678]\d{9}','13111111111') print(result.group()) #匹配成功 result = re.match(r'1[35678]\d{9}','12111111111') print(result) #none,第二位為2 result = re.match(r'1[35678]\d{9}','121111111112') print(result) #none,有12位
提取網(wǎng)頁源碼中所有的文字
如下,將其中的所有文字提取出來,去掉標(biāo)簽。思路就是運用sub方法,將標(biāo)簽替換為空
s = """<div> <p>崗位職責(zé):</p> <p>完成推薦算法、數(shù)據(jù)統(tǒng)計、接口、后臺等服務(wù)器端相關(guān)工作</p> <p><br></p> <P>必備要求:</p> <p>良好的自我驅(qū)動力和職業(yè)素養(yǎng),工作積極主動、結(jié)果導(dǎo)向</p> <p> <br></p> <p>技術(shù)要求:</p> <p>1、一年以上 Python開發(fā)經(jīng)驗,掌握面向?qū)ο蠓治龊驮O(shè)計,了解設(shè)計模式</p> <p>2、掌握HTTP協(xié)議,熟悉NVC、MVVM等概念以及相關(guān)wEB開發(fā)框架</p> <p>3、掌握關(guān)系數(shù)據(jù)庫開發(fā)設(shè)計,掌握SQL,熟練使用 MySQL/PostgresQL中的一種<br></p> <p>4、掌握NoSQL、MQ,熟練使用對應(yīng)技術(shù)解決方案</p> <p>5、熟悉 Javascript/cSS/HTML5,JQuery,React.Vue.js</p> <p> <br></p> <p>加分項:</p> <p>大數(shù)據(jù),數(shù)理統(tǒng)計,機器學(xué)習(xí),sklearn,高性能,大并發(fā)。</p> </div>"""
要提取出來最重要的就是關(guān)閉貪婪模式,
result = re.sub(r'<.*?>| ','',s) # print(result)
如果關(guān)閉貪婪模式,<xx>中的內(nèi)容會盡可能多的匹配,只要能夠滿足后面的>就行,然后<>xxx<>中xxx內(nèi)容也替換掉了
提取圖片地址
import re s = """<img data-original="https://img02.sogoucdn.com/app/a/100520024/36189693dc8db6bd7c0be389f8aaddbd.jpg" src="https://img02.sogoucdn.com/app/a/100520024/36189693dc8db6bd7c0be389f8aaddbd.jpg" width="250" height="375" .jpg>""" result1 = re.search(r"src=\"https.*.jpg\"",s) print(result1.group()) result2 = re.search(r"src=\"(https.*.jpg)\"",s) #我只是想將網(wǎng)址提取出來,所以httpxx加括號,這樣我就可以把它單獨提取出來,src則不會出來 print(result2.groups()[0])
總結(jié)
到此這篇關(guān)于Python正則表達式re模塊詳解的文章就介紹到這了,更多相關(guān)Python正則表達式re模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用Openpyxl操作Excel文件的實現(xiàn)
openpyxl 是一個用于在 Python 中讀取和寫入 Excel 文件的優(yōu)秀庫,本文主要介紹了python使用Openpyxl操作Excel文件的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2025-04-04pycharm遠(yuǎn)程連接服務(wù)器調(diào)試tensorflow無法加載問題
最近打算在win系統(tǒng)下使用pycharm開發(fā)程序,并遠(yuǎn)程連接服務(wù)器調(diào)試程序,其中在import tensorflow時報錯,本文就來介紹一下如何解決,感興趣的可以了解一下2021-06-06