python的正則表達(dá)式re模塊的常用方法
使用python的re模塊,盡管不能滿足所有復(fù)雜的匹配情況,但足夠在絕大多數(shù)情況下能夠有效地實(shí)現(xiàn)對復(fù)雜字符串的分析并提取出相關(guān)信息。python 會(huì)將正則表達(dá)式轉(zhuǎn)化為字節(jié)碼,利用 C 語言的匹配引擎進(jìn)行深度優(yōu)先的匹配。
import re
print re.__doc__
可以查詢r(jià)e模塊的功能信息,下面會(huì)結(jié)合幾個(gè)例子說明。
2.re的正則表達(dá)式語法
正則表達(dá)式語法表如下:
| 語法 | 意義 | 說明 |
| "." | 任意字符 | |
| "^" | 字符串開始 | '^hello'匹配'helloworld'而不匹配'aaaahellobbb' |
| "$" | 字符串結(jié)尾 | 與上同理 |
| "*" |
0 個(gè)或多個(gè)字符(貪婪匹配) |
<*>匹配<title>chinaunix</title> |
| "+" |
1 個(gè)或多個(gè)字符(貪婪匹配) |
與上同理 |
| "?" |
0 個(gè)或多個(gè)字符(貪婪匹配) |
與上同理 |
| *?,+?,?? |
以上三個(gè)取第一個(gè)匹配結(jié)果(非貪婪匹配) | <*>匹配<title> |
| {m,n} |
對于前一個(gè)字符重復(fù)m到n次,{m}亦可 |
a{6}匹配6個(gè)a、a{2,4}匹配2到4個(gè)a |
| {m,n}? |
對于前一個(gè)字符重復(fù)m到n次,并取盡可能少 |
‘a(chǎn)aaaaa'中a{2,4}只會(huì)匹配2個(gè) |
| "\\" |
特殊字符轉(zhuǎn)義或者特殊序列 | |
| [] |
表示一個(gè)字符集 | [0-9]、[a-z]、[A-Z]、[^0] |
| "|" |
或 | A|B,或運(yùn)算 |
| (...) |
匹配括號中任意表達(dá)式 | |
| (?#...) |
注釋,可忽略 | |
| (?=...) |
Matches if ... matches next, but doesn't consume the string. |
'(?=test)' 在hellotest中匹配hello |
| (?!...) |
Matches if ... doesn't match next. |
'(?!=test)' 若hello后面不為test,匹配hello |
| (?<=...) |
Matches if preceded by ... (must be fixed length). |
'(?<=hello)test' 在hellotest中匹配test |
| (?<!...) |
Matches if not preceded by ... (must be fixed length). |
'(?<!hello)test' 在hellotest中不匹配test |
正則表達(dá)式特殊序列表如下:
| 特殊序列符號 |
意義 |
| \A |
只在字符串開始進(jìn)行匹配 |
| \Z |
只在字符串結(jié)尾進(jìn)行匹配 |
| \b |
匹配位于開始或結(jié)尾的空字符串 |
| \B |
匹配不位于開始或結(jié)尾的空字符串 |
| \d |
相當(dāng)于[0-9] |
| \D |
相當(dāng)于[^0-9] |
| \s |
匹配任意空白字符:[\t\n\r\r\v] |
| \S |
匹配任意非空白字符:[^\t\n\r\r\v] |
| \w |
匹配任意數(shù)字和字母:[a-zA-Z0-9] |
| \W |
匹配任意非數(shù)字和字母:[^a-zA-Z0-9] |
3.re的主要功能函數(shù)
常用的功能函數(shù)包括:compile、search、match、split、findall(finditer)、sub(subn)
compile
re.compile(pattern[, flags])
作用:把正則表達(dá)式語法轉(zhuǎn)化成正則表達(dá)式對象
flags定義包括:
re.I:忽略大小寫
re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依賴于當(dāng)前環(huán)境
re.M:多行模式
re.S:' . '并且包括換行符在內(nèi)的任意字符(注意:' . '不包括換行符)
re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依賴于 Unicode 字符屬性數(shù)據(jù)庫
search
re.search(pattern, string[, flags])
search (string[, pos[, endpos]])
作用:在字符串中查找匹配正則表達(dá)式模式的位置,返回 MatchObject 的實(shí)例,如果沒有找到匹配的位置,則返回 None。
match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函數(shù)只在字符串的開始位置嘗試匹配正則表達(dá)式,也就是只報(bào)告從位置 0 開始的匹配情況,而 search() 函數(shù)是掃描整個(gè)字符串來查找匹配。如果想要搜索整個(gè)字符串來尋找匹配,應(yīng)當(dāng)用 search()。
下面是幾個(gè)例子:
例:最基本的用法,通過re.RegexObject對象調(diào)用
#!/usr/bin/env python
import re
r1 = re.compile(r'world')
if r1.match('helloworld'):
print 'match succeeds'
else:
print 'match fails'
if r1.search('helloworld'):
print 'search succeeds'
else:
print 'search fails'
說明一下:r是raw(原始)的意思。因?yàn)樵诒硎咀址杏幸恍┺D(zhuǎn)義符,如表示回車'\n'。如果要表示\表需要寫為'\\'。但如果我就是需要表示一個(gè)'\'+'n',不用r方式要寫為:'\\n'。但使用r方式則為r'\n'這樣清晰多了。
例:設(shè)置flag
#r2 = re.compile(r'n$', re.S)
#r2 = re.compile('\n$', re.S)
r2 = re.compile('World$', re.I)
if r2.search('helloworld\n'):
print 'search succeeds'
else:
print 'search fails'
例:直接調(diào)用
if re.search(r'abc','helloaaabcdworldn'):
print 'search succeeds'
else:
print 'search fails'
split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以將字符串匹配正則表達(dá)式的部分割開并返回一個(gè)列表
例:簡單分析ip
#!/usr/bin/env python
import re
r1 = re.compile('W+')
print r1.split('192.168.1.1')
print re.split('(W+)', '192.168.1.1')
print re.split('(W+)', '192.168.1.1', 1)
結(jié)果如下:
['192', '168', '1', '1']
['192', '.', '168', '.', '1', '.', '1']
['192', '.', '168.1.1']
findall
re.findall(pattern, string[, flags])
findall(string[, pos[, endpos]])
作用:在字符串中找到正則表達(dá)式所匹配的所有子串,并組成一個(gè)列表返回
例:查找[]包括的內(nèi)容(貪婪和非貪婪查找)
#!/usr/bin/env python
import re
r1 = re.compile('([.*])')
print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")
r1 = re.compile('([.*?])')
print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")
print re.findall('[0-9]{2}',"fdskfj1323jfkdj")
print re.findall('([0-9][a-z])',"fdskfj1323jfkdj")
print re.findall('(?=www)',"afdsfwwwfkdjfsdfsdwww")
print re.findall('(?<=www)',"afdsfwwwfkdjfsdfsdwww")
finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
說明:和 findall 類似,在字符串中找到正則表達(dá)式所匹配的所有子串,并組成一個(gè)迭代器返回。同樣 RegexObject 有:
sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
說明:在字符串 string 中找到匹配正則表達(dá)式 pattern 的所有子串,用另一個(gè)字符串 repl 進(jìn)行替換。如果沒有找到匹配 pattern 的串,則返回未被修改的 string。Repl 既可以是字符串也可以是一個(gè)函數(shù)。
例:
#!/usr/bin/env python
import re
p = re.compile('(one|two|three)')
print p.sub('num', 'one word two words three words apple', 2)
subn
re.subn(pattern, repl, string[, count, flags])
subn(repl, string[, count=0])
說明:該函數(shù)的功能和 sub() 相同,但它還返回新的字符串以及替換的次數(shù)。同樣 RegexObject 有:
相關(guān)文章
OpenCV實(shí)現(xiàn)相機(jī)標(biāo)定
這篇文章主要為大家詳細(xì)介紹了OpenCV實(shí)現(xiàn)相機(jī)標(biāo)定,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
python腳本監(jiān)控logstash進(jìn)程并郵件告警實(shí)例
這篇文章主要介紹了python腳本監(jiān)控logstash進(jìn)程并郵件告警實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python網(wǎng)絡(luò)編程之網(wǎng)絡(luò)與通信介紹
這篇文章主要介紹了Python網(wǎng)絡(luò)編程之網(wǎng)絡(luò)與通信介紹,計(jì)算機(jī)網(wǎng)絡(luò)就是分布在不同的地區(qū)的計(jì)算機(jī)與專門的外部設(shè)備通信線路互聯(lián)在一起,2023-08-08
成為一個(gè)功能強(qiáng),規(guī)模大的網(wǎng)絡(luò)系統(tǒng),本期就主要介紹網(wǎng)絡(luò)與通信的相關(guān)知識和原理,需要的朋友可以參考下
使用Python進(jìn)行數(shù)獨(dú)求解詳解(一)
本文主要介紹了如何構(gòu)建一個(gè)Python腳本來解決數(shù)獨(dú)難題,本文的重點(diǎn)在于介紹用于構(gòu)建數(shù)獨(dú)求解器的回溯算法。感興趣的小伙伴可以學(xué)習(xí)一下2022-02-02
python 實(shí)現(xiàn)分頁顯示從es中獲取的數(shù)據(jù)方法
今天小編就為大家分享一篇python 實(shí)現(xiàn)分頁顯示從es中獲取的數(shù)據(jù)方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python中使用PyHook監(jiān)聽鼠標(biāo)和鍵盤事件實(shí)例
這篇文章主要介紹了Python中使用PyHook監(jiān)聽鼠標(biāo)和鍵盤事件實(shí)例,這個(gè)庫依賴于另一個(gè)Python庫PyWin32,并且只能運(yùn)行在Windows平臺,需要的朋友可以參考下2014-07-07
Python視頻剪輯合并操作的實(shí)現(xiàn)示例
很多人在創(chuàng)作視頻時(shí)都需要進(jìn)行剪輯,本文主要介紹了Python視頻剪輯合并操作的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
使用icecream實(shí)現(xiàn)優(yōu)雅調(diào)試Python代碼
在大型項(xiàng)目中,使用print()調(diào)試代碼可能導(dǎo)致終端輸出過多,難以分辨輸出結(jié)果與代碼的對應(yīng)關(guān)系,為了更清晰地調(diào)試,可以采用Icecream庫,本文介紹了如何使用icecream實(shí)現(xiàn)優(yōu)雅調(diào)試Python代碼,需要的朋友可以參考下2024-08-08

