簡單介紹python中使用正規表示式的方法
導讀 | 這篇文章主要為大家詳細介紹了python中使用正規表示式的方法,文中示例程式碼介紹的非常詳細,具有一定的參考價值,感興趣的小夥伴們可以參考一下,希望能夠給你帶來幫助 |
在python中使用正規表示式,主要透過下面的幾個方法
search(pattern, string, flags=0)
掃描整個string並返回匹配pattern的結果(None或物件)
有匹配的字串的話返回一個物件(包含符合匹配條件的第一個字串),否則返回None
import re #匯入正則庫 content = 'Hello 1234567 Hello 666' #要匹配的文字 res = 'Hello\s' #正則字串 result = re.search(res, content) if result is not None: print(result.group()) #輸出匹配得到的字串 'hello'(返回的得是第一個'hello') print(result.span()) #輸出輸出匹配的範圍(匹配到的字串在原字串中的位置的範圍) res1 = 'Hello\s(\d)(\d+)' result = re.search(res1, content) print(result.group(1)) #group(1)表示匹配到的第一個組(即正則字串中的第一個括號)的內容 print(result.group(2))
findall(pattern, string, flags=0)
掃描整個context並返回匹配res的結果(None或列表)
有匹配的字串的話返回一個列表(符合匹配條件的每個子字串作為它的一個元素),否則返回None
import re res = 'Hello\s' results = re.findall(res, content) if results is not None: print(results) #輸出: ['hello','hello'] res1 = 'Hello\s(\d)(\d+)' results = re.findall(res1, content) if result is not None: print(results) # 當正則字串中出現括號時,所得到列表的每個元素是元組 # 每個元組的元素都是依次匹配到的括號內的表示式的結果 #輸出: [('1','1234567'),('6','666')]
sub(pattern, repl, string, count=0, flags=0)
可以來修改文字
用將用pattern匹配string所得的字串替換成repl
import re content = '54aK54yr5oiR54ix5L2g' res = '\d+' content = re.sub(res, '', content) print(content)
compile(pattern, flags=0)
將正規表示式res編譯成一個正則物件並返回,以便複用
import re content1 = '2019-12-15 12:00' content2 = '2019-12-17 12:55' content3 = '2019-12-22 13:21' pattern = re.compile('\d{2}:\d{2}') result1 = re.sub(pattern, '', content1) result2 = re.sub(pattern, '', content2) result3 = re.sub(pattern, '', content3) print(result1, result2, result3)
flags的一些常用值
re.I 使匹配對大小寫不敏感
re.S 使.匹配包括換行符在內的所有字元
import re re.compile(res, re.I) #如果res可以匹配大寫字母,那它也可以匹配相應的小寫字母,反之也可 re.compile(res,re.S) #使res中的'.'字元可以匹配包括換行符在內的所有字元
原文來自:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2887478/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Python模組(module)
- python常識系列07-->python利用xlwt寫入excel檔案
- 一種將函式模板定義和宣告分開的方法
- 交流學習SAP ERP的各種問題和方法,如何快速入行?
- Python語言初學者?風變程式設計更適合
- 功德+N!Python敲擊木魚積累功德程式碼
- 6道常見的python面試題,你答對了嗎?
- 如何快速傳輸大檔案:4 種大檔案傳輸有效的方法
- transforms模組—PyTorch影像處理與資料增強方法
- 舊酒換新瓶,新版M1/M2晶片Macos(Ventura)安裝古早版本Python2.7(Python2.x)
- 硬碟使用驅動器中的光碟之前需要將其格式化修復方法?
- SICP:符號求導、集合表示和Huffman樹(Python實現)
- Python Kconfiglib初次學習