1 回答

TA貢獻1804條經驗 獲得超3個贊
如果您假設字符串中至少有一個并且在它之后至少有一個,那么在您的主要驗證正則表達式失敗時,您可以捕獲電子郵件的三個部分,并從中刪除所有不需要的字符并連接回一個“干凈的@” .“ 電子郵件:
import re
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$'
text = "t'[email protected]"
def repl(x):
return "{}@{}.{}".format(re.sub(r'[^a-zA-Z0-9_.+-]+', '', x.group(1)),
re.sub(r'[^a-zA-Z0-9.-]+', '', x.group(2)),
re.sub(r'[^a-zA-Z0-9.-]+', '', x.group(3)))
if re.fullmatch(pattern, text):
print("Valid email: {}".format(text))
else:
email = re.sub(r"(.*)@(.*)\.(.*)", repl, text)
print("Filtered email: {}".format(email))
查看Python 演示,輸出為Filtered email: [email protected]
.
還有另一種清理部分的方法@:拆分.并刪除所有字符[^a-zA-Z0-9-]+中匹配的所有字符,然后將它們連接回去:
def repl(x):
return "{}@{}".format(re.sub(r'[^a-zA-Z0-9_.+-]+', '', x.group(1)),
".".join([re.sub(r'[^a-zA-Z0-9-]+', '', y) for y in x.group(2).split('.')]) )
請參閱此 Python 演示。
添加回答
舉報