1.首先,re模塊是python自帶的模塊,使用import re就可以使用了
2.基礎語法我就不說了。主要進行總結
match,search都是只匹配一次的。匹配到就返回match對象了。后面是否有可以匹配到的是不管的,如果match開頭沒有匹配到,返回none,search在整個字符串中么有匹配到返回none
findall,split返回字符串列表。findall返回匹配到的所有,split以pattern作為分隔符進行分割,並且刪除pattern的內容,如果想獲取非空的列表,可以while '' in result:result.remove('')
import re # 1-9開頭后接5位數字 pattern = r'[1-9]\d{5}' txt = 'a 123546 is this a s123456123456123456 sda123456 23' result = re.split(pattern, txt) print(result) while '' in result: result.remove('') print(result) ########################### #['a ', ' is this a s', '', '', ' sda', ' 23'] #['a ', ' is this a s', ' sda', ' 23']
.sub(pattern,replace,txt)替換,就像notepad里的替換一樣,沒什么好說的。返回結果是替換后的字符串