python re 模組小結

2021-09-27 09:28:49 字數 1537 閱讀 6356

前言:

本人環境windows 7 64

位,python2.7

re是什麼:

regular expression縮寫,意為正規表示式,是

python

的眾多模組之一

re用途:

從文字中有選擇的批量抽取想要的文字碎片

re型別:

分為dfa(

確定的有窮狀態自動機)和

nfa(

非確定的有窮狀態自動機)

re的安裝:

開啟dos;cd

到pip

目錄下;輸入命令

pip install re

re常用方法:

1.re.compile(pattern, flags=0)

pattern是

str型別的,例:

pattern  = r『^.*?$』

2.re.findall(pattern, string, flags=0)例1:

print re.findall(r』(s)(d)』, 『gsd sd fsa ggh sd hf sdgf 』)

結果:[('s', 'd'), ('s', 'd'), ('s', 'd'), ('s', 'd')]

例2:print re.findall(r'(s)d','gsd sd fsa ggh sd hf sdgf')

結果:['s', 's', 's', 's']

例3:print re.findall(r'sd','gsd sd fsa ggh sd hf sdgf')

結果:['sd', 'sd', 'sd', 'sd']

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

split the source string by the occurrences of the pattern,

returning a list containing the resulting substrings.返回list

例:print re.split(r's','jsjkjoishioshuisguusnjshbsg')

結果:['j', 'jkjoi', 'hio', 'hui', 'guu', 'nj', 'hb', 'g']

用途:將大段文字分成易於處理的小片段

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

a match object, or none if no match was found.返回的object類似指標

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

scan through string looking for a match to the pattern, returning

a match object, or none if no match was found.返回的object類似指標

Python re 正則模組

有些字元比較特殊,它們和自身並不匹配,而是會表明應和一些特殊的東西匹配,或者它們會影響到 re 其它部分的重複次數,它們叫元字元。其中 m 和 n 是十進位制整數。該限定符的意思是至少有 m 個重複,至多到 n 個重複。舉個例子,a b 將匹配 a b a b 和 a b 它不能匹配 ab 因為沒有...

Python re正則模組

對於比較複雜的字串處理任務,需要依靠正規表示式。首先需要匯入 re 模組 import re常用的元字元 符號含義 匹配除 n 和 r 之外的任何單個字元。匹配字串開始位置 匹配字串結束位置 前面的元素重複0次,1次或多次 前面的元素重複0次或1次 前面的元素重複1次或多次 前面的元素出現了n次 前...

Python re模組學習

這是re模組與正則的結合 re模組提供的函式 1.match 嘗試在字串的開頭應用該模式,返回匹配物件,如果沒有找到匹配,則為none。1 importre2 3 str1 why are you keeping this curiosity door locked?4 res re.match w...