查找 findall, match, search
import re
def re_match_common(pattern, string, mathod, flags = re.I|re.M):
"""正則查找通用函數
:param pattern: 正則表達式
:param string: 可用於查找的字符串
:param mathod: 查找方法:find,findall,match,search
:param flags: 可選標誌修飾符,默認re.I(忽略大小寫)|re.M(多行查找)
:return result: 匹配結果
"""
regex = re.compile(pattern=pattern, flags=flags)
if mathod=='findall':
# 返回所有匹配項--列表
result_findall = regex.findall(string)
return result_findall
elif mathod=='match':
# 只匹配字符串的首部,返回match對象
try:
match_ = regex.match(string).group()
result_match = string[match_.start() : match_.end()]
print('match匹配成功!')
except:
result_match = None
print('match匹配失敗!')
finally:
return result_match
elif mathod=='search':
# 返回第一個匹配項
search_ = regex.search(string)
result_search = string[search_.start() : search_.end()]
return result_search
if __name__=='__main__':
text = """Dave [email protected]
Steve [email protected]
Rob [email protected]
Ryan [email protected]
"""
pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
re_match_common(pattern, text, mathod='findall')
替換 sub
sub⽅法可以將匹配到的模式替換爲指定字符串,並返回所得到的新字符串
print(regex.sub('REDACTED', text))