re模組方法
阿新 • • 發佈:2018-12-15
findall
查詢所有匹配項,返回的是一個列表
import re
re.findall("\d+", "alex12lucy22")
# ["12", "22"]
search
只返回第一次匹配項,返回一個group物件
import re
re.search("\d+", "alex12lucy22").group()
# "12"
match
只在開始位置匹配一次
import re re.match("\d+", "alex12lucy22").group() # re.match("[a-z]+", "alex12lucy22").group() # "alex"
split
import re
re.split("[ab]", "ahighabwest")
# 按照a分割成 ['', 'high', 'bwest']
# 再按照b分割成['', 'high', '', 'west']
# ['', 'high', '', 'west']
sub
字串替換
import re
re.sub("\d+", "dog", "You 666!")
# 'You dog!'
import re re.sub("\d+", "dog", "You 666 999!") # 'You dog dog!' re.sub("\d+", "dog", "You 666 999!", 1) # 'You dog 999!'
subn
返回一個元組,包括替換後的字串和替換次數
import re
re.subn("\d+", "dog", "You 666 999!", 1)
# ('You dog 999!', 1)
compile
一個正則表示式方便多次使用
import re reg = re.compile("\d+") reg.search("lucy22cuci19") # <re.Match object; span=(4, 6), match='22'> reg.search("lucy22cuci19").group() # '22' reg.search("wanjia29xifeng36") # <re.Match object; span=(6, 8), match='29'> reg.search("wanjia29xifeng36").group() # '29'
finditer
返回一個遍歷器物件
import re
arr = re.finditer("\d+", "lucy22cuci19")
next(arr).group()
# '22'