本文實例講述了Python3正則匹配re.split,re.finditer及re.findall函數用法。分享給大家供大家參考,具體如下:
re.split re.finditer re.findall
@(python3)
官方 re 模塊說明文檔
re.compile() 函數
編譯正則表達式模式,返回一個對象。可以把常用的正則表達式編譯成正則表達式對象,方便后續調用及提高效率。
re 模塊最離不開的就是 re.compile 函數。其他函數都依賴于 compile 創建的 正則表達式對象
re.compile(pattern, flags=0)
flags 標志位參數
re.I(re.IGNORECASE)
使匹配對大小寫不敏感
re.L(re.LOCAL)
做本地化識別(locale-aware)匹配
re.M(re.MULTILINE)
多行匹配,影響 ^ 和 $
re.S(re.DOTALL)
使 . 匹配包括換行在內的所有字符
re.U(re.UNICODE)
根據Unicode字符集解析字符。這個標志影響 /w, /W, /b, /B.
re.X(re.VERBOSE)
該標志通過給予你更靈活的格式以便你將正則表達式寫得更易于理解。
示例:
import recontent = 'Citizen wang , always fall in love with neighbour,WANG'rr = re.compile(r'wan/w', re.I) # 不區分大小寫print(type(rr))a = rr.findall(content)print(type(a))print(a)
findall 返回的是一個 list 對象
<class '_sre.SRE_Pattern'>
<class 'list'>
['wang', 'WANG']
re.split 函數
按照指定的 pattern 格式,分割 string 字符串,返回一個分割后的列表。
re.split(pattern, string, maxsplit=0, flags=0)
import restr = 'say hello world! hello python'str_nm = 'one1two2three3four4'pattern = re.compile(r'(?P<space>/s)') # 創建一個匹配空格的正則表達式對象pattern_nm = re.compile(r'(?P<space>/d+)') # 創建一個匹配空格的正則表達式對象match = re.split(pattern, str)match_nm = re.split(pattern_nm, str_nm, maxsplit=1)print(match)print(match_nm)
結果:
['say', ' ', 'hello', ' ', 'world!', ' ', 'hello', ' ', 'python']
['one', '1', 'two2three3four4']
re.findall() 方法
返回一個包含所有匹配到的字符串的列表。
pattern 匹配模式,由 re.compile 獲得 string 需要匹配的字符串import restr = 'say hello world! hello python'pattern = re.compile(r'(?P<first>h/w)(?P<symbol>l+)(?P<last>o/s)') # 分組,0 組是整個 world!, 1組 or,2組 ld!match = re.findall(pattern, str)print(match)
新聞熱點
疑難解答