給我你的 email
同事向你求助!當使用者在公司網站註冊時,必須提供有效的 email 位址。 公司制定了以下規則來驗證 email 是否有效:
- 第一部分可以包含:
- 大寫
A-Z或小寫a-z的英文字母 - 數字
- 這些字元:
!、#、%、&、*、$、.
- 大寫
- 必須有
@ - 網域部分:
- 可以包含任意單字字元
- 但僅允許以
.com作為結尾
這個專案要你撰寫一個腳本,用來檢查 email 位址是否符合正確的樣式。你的同事提供了一份 email 範例清單讓你測試。
清單 emails 與模組 re 已經在你的工作階段中載入。你可以使用 print(emails) 在 IPython Shell 中查看這些 email。
本練習屬於課程
Python 中的正規表示法
練習說明
- 撰寫一個符合上述規則的正則表示式,用來匹配有效的 email 位址。
- 將該正則表示式套用到
emails中的各個元素。 - 若要印出是否為有效 email 的訊息,請完成
.format()陳述式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Write a regex to match a valid email address
regex = ____"[____]____@____\.com"
for example in emails:
# Match the regex to the string
if re.____(____, ____):
# Complete the format method to print out the result
print("The email {____} is a valid email".____(email_example=____))
else:
print("The email {____} is invalid".____(email_example=____))