国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3正則匹配re.split,re.finditer及re.findall函數用法詳解

2020-02-15 21:48:09
字體:
來源:轉載
供稿:網友

本文實例講述了Python3正則匹配re.split,re.finditer及re.findall函數用法。分享給大家供大家參考,具體如下:

re.split re.finditer re.findall

@(python3)

官方 re 模塊說明文檔

re.compile() 函數

編譯正則表達式模式,返回一個對象??梢园殉S玫恼齽t表達式編譯成正則表達式對象,方便后續調用及提高效率。

re 模塊最離不開的就是 re.compile 函數。其他函數都依賴于 compile 創建的 正則表達式對象

re.compile(pattern, flags=0)

pattern 指定編譯時的表達式字符串 flags 編譯標志位,用來修改正則表達式的匹配方式。支持 re.L|re.M 同時匹配

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)

pattern compile 生成的正則表達式對象,或者自定義也可 string 要匹配的字符串 maxsplit 指定最大分割次數,不指定將全部分割
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)            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洪雅县| 平凉市| 德保县| 新余市| 庆阳市| 大港区| 疏勒县| 壤塘县| 化德县| 云阳县| 葵青区| 怀远县| 龙泉市| 常宁市| 化州市| 大新县| 长汀县| 灵璧县| 茶陵县| 股票| 新津县| 齐齐哈尔市| 札达县| 大庆市| 佛学| 武义县| 双桥区| 虞城县| 灵山县| 敦煌市| 天门市| 黄陵县| 白水县| 镇原县| 隆回县| 台北市| 宜丰县| 随州市| 宜昌市| 高陵县| 福贡县|