1. 程式人生 > >python re模組常用方法總結

python re模組常用方法總結

res = re.match(pattern, string, flags=0)
#字串的開頭是否能匹配正則表示式。返回_sre.SRE_Match物件,如果
#不能匹配返回None。
# 如果匹配的話,res.string可以獲得原始的字串,並不是匹配的字串 
re.sub(pattern, repl, string, count=0, flags=0)

#找到 RE 匹配的所有子串,並將其用repl替換。可選引數 
#count 是模式匹配後替換的最大次數;count 必須是非負整數。預設值
#是 0 表示替換所有的匹配。如果無匹配,字串將會無改變地返回。如
#果有匹配,則返回替換後的字串
# pattern='he$' 尾部匹配 # pattern='^he' 頭部匹配,等價於match
re.findall(pattern,string)
# 從 string中找到所有 匹配 pattern的子串,作為列表返回
#如果沒有匹配的話,返回空陣列,可用來當做if的判斷條件
#空陣列為False
# pattern='he$' 尾部匹配
# pattern='^he' 頭部匹配,等價於match
re.search(pattern, string)
#顧名思義,查詢,如果找到返回一個match物件,找不到,返回None。
# pattern='he$' 尾部匹配
# pattern='^he' 頭部匹配,等價於match

參考資料