python re 正则表达式
??正則表達(dá)式是用于字符串搜索、匹配、替換的常見方法,而它實際上就是一個特殊的字符序列,用來幫助你方便的檢查一個字符串是否與某種模式匹配。 Python中re包是專門用來處理正則表達(dá)式的相關(guān)操作,我參考了一些資料整理了re包中所有的函數(shù)應(yīng)用,僅供參考!
?
?說明:以下所有函數(shù)均是(均可)re.funcname(),也就是說正則表達(dá)式具有兩種編程手法,使用方式基本相同,但是函數(shù)參數(shù)略有不同,使用時注意就好!
方法1
? re.function();
方法2
? obj = re.compile();
? obj.funcname();
compile()
??compile()函數(shù)根據(jù)一個模式字符串和可選的標(biāo)志參數(shù)生成一個正則表達(dá)式對象。該對象擁有一系列方法用于正則表達(dá)式匹配和替換,所謂一系列方法即是包括下面要介紹的所有函數(shù),而下面所有函數(shù)又可以通過re.funcname()調(diào)用,這一點要非常注意!
re.compile(pattern='regex_exp', flags=re.I)
- pattern : 一個字符串形式的正則表達(dá)式
- flags : 可選,表示匹配模式,比如忽略大小寫,多行模式等,具體參數(shù)為:
- 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ù)庫
- re.X 為了增加可讀性,忽略空格和 # 后面的注釋
match()
??如前所述,re.match()嘗試從字符串的起始位置匹配一個模式,如果匹配成功則返回一個Match對象,反之返回none
import re print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 (0,3) print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配 Nonefullmatch()
??這個好理解,要求完全匹配
import res = '234d' matched = re.fullmatch('\d+', s, 0) if matched:print(matched.group()) else:print('not matched')# not matchedsearch()
??re.search 掃描整個字符串并返回第一個成功的匹配(Match對象),否則返回None
line = "Cats are smarter than dogs" searchObj = re.search(r'(.*) are (.*?) .*', line, re.M | re.I) # print(type(searchObj)) # Match對象 if searchObj:# 這是第二個提到分組的例子# 分組是對匹配結(jié)果的一個分組,體現(xiàn)在正則表達(dá)式的()上,一個()代表建立一個分組print("searchObj.group() : ", searchObj.group())print("searchObj.group(1) : ", searchObj.group(1))print("searchObj.group(2) : ", searchObj.group(2)) else:print("Nothing found!!")# searchObj.group() : Cats are smarter than dogs # searchObj.group(1) : Cats # searchObj.group(2) : smartersub()
??sub()函數(shù)用于字符串替換,原型:re.sub(pattern, repl, string, count=0, flags=0),說明一下,count是指模式匹配后替換的最大次數(shù),默認(rèn) 0 表示替換所有的匹配;repl(replace)表示替換的字符串,也可為一個函數(shù)。
# repl 作為一個字符串 import renum = "2018-08-17" new_num = re.sub(r"\D", "", num, count=0) print(new_num)# 20180817 # repl作為一個函數(shù) # 將匹配的數(shù)字乘以 2 def double(matched):value = int(matched.group('value'))return str(value * 2)s = 'A23G4HFD567' new_str = re.sub(r'(?P<value>\d+)', double, s) print(new_str) # A46G8HFD1134subn
subn()函數(shù)基本同sub()函數(shù),唯一不同點是subn()還會返回替代次數(shù),例子如下:
s = 'A23G4HFD567' n = re.subn(r'(?P<value>\d+)', '', s) print(n)# ('AGHFD', 3) 返回一個tuple。根據(jù)具體情境選用sub() or subn()findall()
??在字符串中找到正則表達(dá)式所匹配的所有子串,并返回一個列表,如果沒有找到匹配的,則返回空列表,而上面提到的match()、search()函數(shù)匹配一次且返回對象為Match或None.
s = 'A23G4HFD567' # flags其實和上面一樣,不過這里我用的是 int類型數(shù)來表示 # 具體對應(yīng)關(guān)系,我...也記不住! print(re.findall(r'\d+', s, flags=0))# ['23', '4', '567']finditer()
??和 findall 類似,在字符串中找到正則表達(dá)式所匹配的所有子串,并把它們作為一個迭代器返回,具有更好的性能。
s = 'A23G4HFD567' iter = re.finditer(r'\d+', s, flags=0)for match in iter:print(match.group())# 23 # 4 # 567split()
??split 方法按照能夠匹配的子串將字符串分割后返回列表,在很多其他語言也有這個函數(shù),如C#,java。在函數(shù)中,maxsplit表示分隔次數(shù),maxsplit=1 分隔一次,默認(rèn)為 0,不限制次數(shù)。
import re s = 'A23G4HFD567N' res = re.split(r'\d+', s, maxsplit=2, flags=0) print(res)# ['A', 'G', 'HFD567N']escape()
??可以對字符串中所有可能被解釋為正則運算符的字符進(jìn)行轉(zhuǎn)義的應(yīng)用函數(shù)。如果字符串很長且包含很多特殊技字符,而你又不想輸入一大堆反斜杠,例子:
s = 'A23G4HFD567N'# Escape all the characters in pattern except ASCII letters, numbers and '_'. # re.escape('www.python.org') # 返回值 strres = re.findall(re.escape('*+.py'), "jw.pyji w.py.f") print(res)# ['w.py', 'w.py']purge()
??無參函數(shù),用于清空緩存中的正則表達(dá)式,用于末尾,就好比其他語言中的close()、flush(),用來做相應(yīng)的收尾工作。
Match Object
??Match對象在前面的例子中已經(jīng)有例子了,提出來主要是為了更全面、更清晰。re.match()和re.search()函數(shù)如果匹配成功都會返回一個match對象,這里主要看看Match對象的一些方法應(yīng)用。
import res = '234d567gg' matched = re.search(r'(\d+)\w(\d+)', s, flags=0)if matched:print(matched.groups()) # ('234', '567')print(matched.group()) # 234d567print(matched.group(1)) # 234print(matched.group(2)) # 567print(matched.span()) # (0,7)print(matched.start(0)) # 0print(matched.end(0)) # 7print(matched.expand(r'\2 \1')) # 567 234 type is str# 注意這下面的用法 python3.6及以上才有的print(matched[0]) # 234d567print(matched[1]) # 234print(matched[2]) # 567# 屬性print(matched.pos) # 0print(matched.endpos) # 7print(matched.string) # 234d567print(matched.re) # 返回的是regular expression objectprint(matched.lastindex) # 2,這個2指的是 matched[i]print(matched.lastgroup) # None 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的python re 正则表达式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux 后台运行程序方法总结
- 下一篇: Pandas处理数据缺失值