天天看點

re子產品方法

1.re.match

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

re.match 嘗試從字元串的起始位置比對一個模式,如果不是起始位置比對成功的話,match()就傳回none。

比對成功re.match方法傳回一個比對的對象,否則傳回None。group(num) 或 groups() 比對對象函數來擷取比對表達式

2.re.search

re.search 掃描整個字元串并傳回第一個成功的比對

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

re.match與re.search的差別

re.match隻比對字元串的開始,如果字元串開始不符合正規表達式,則比對失敗,函數傳回None;而re.search比對整個字元串,直到找到一個比對。

3.re.compile 

compile 函數用于編譯正規表達式,生成一個正規表達式( Pattern )對象,供 match() 和 search() 這兩個函數使用。

re.compile(pattern[, flags])      

4.findall

在字元串中找到正規表達式所比對的所有子串,并傳回一個清單,如果沒有找到比對的,則傳回空清單。

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

5.re.finditer

和 findall 類似,在字元串中找到正規表達式所比對的所有子串,并把它們作為一個疊代器傳回。

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

6.re.split

split 方法按照能夠比對的子串将字元串分割後傳回清單,它的使用形式如下:

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

7.sub方法

使用repl替換string中每一個比對的子串後傳回替換後的字元串 

sub(repl, string[, count])

繼續閱讀