Python——正則表達式 re模塊

Python的正則表達式

Python中使用re模塊提供了正則表達式處理的能力

常量

使用 | 位或 運算開啓多種選項

方法

import re

編譯

re.compile(pattern, flags=0)

設定flags、編譯模式,返回正則表達式對象 regex。

pettern就是正則表達式字符串,flags是選項,正則表達式需要被編譯,爲了提高效率,這些寫編譯後的結果被保存,下次使用同的pattern的時候,就不需要再次版編譯

re的其它方法爲了提高效率都調用了編譯方法,就是爲了提速

單次匹配

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

regex.match(string [,pos [,endpos]])

返回match對象

match匹配從字符串的開頭匹配,regex對象match方法可以重設定個開始位置和結束位置。

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

regex.search(string [,pos [,endpos]])

返回match對象

從頭搜索直到第一個匹配,regex對象serch方法可以衝設定開始位置和結束位置。

re.fullmatch(pattern,string,flags=0)

regex.fullmatch(string [,pos [,endpos]])

返回match對象

整個字符串和正則表達式匹配

全文搜索

re.findall(pattren,string,flags=0)

regex.findall(string [, pos [,endpos]])

對整個字符串,從左至右,返回左右匹配項的列表

如果pattern使用組,列表元素爲組的匹配內容,不使用組,則元素爲匹配內容

re.findeiter(pattern,striing,flags=0)

regex,finditer(string [,pos [,endpos]])

對整個字符串,從左至右,返回所有匹配項返回迭代器

注意:迭代出來的元素爲match對象

匹配替換

re.sub(pattern,replacement,string,count=0,flags=0)

regex.sub(replacement,string,count=0)

返回new_string

使用pattern 對字符串string 進行匹配,對匹配項使用replacement替換

repalcement可以是string、bytes、function

re.subn(pattern,replacement,string,count=0,flags=0)

regex.subn(replacement,string,count=0)

同re.sub 返回一個元組(new_string , number_of_sub_made)

分割字符串

字符串的分割函數split , 太難用,不能指定多個字符進行分割

re.split(pattern,string,maxsplit=0,flags=0)

regex.split(string,maxsplit=0)

分組

使用小括號的pattern捕獲的數據被放到了組group中。

match、search 函數可以返回match對象;findall 返回字符串列表;finditer返回一個個match對象

如果pattern中使用了分組,如果有匹配的結果,會在match對象中:

1.使用,group(n)方式返回對應分組,1~N 是對應的分組,0返回整個匹配的字符串

2.如果使用了命名分組沒,可以使用group(“name”)的方式獲取分組

3.也可以使用groups()返回所有分組

4.使用groupdict()返回所有命名的分組

matchaer.group() 返回 字符串

matchaer.group(‘name’) 返回 字符串

matcher.groups() 返回 分組組成的tuple

matcher.groupdict()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章