共計 531 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 re 模塊中的 findall() 函數來查找字符串中的所有匹配項。
語法:
re.findall(pattern, string, flags=0)
參數說明:
- pattern: 匹配的正則表達式
- string: 要匹配的字符串
- flags: 可選參數,用于控制正則表達式的匹配方式,默認為 0 表示不使用任何標志
示例代碼:
import re
text = "Hello, my name is John. My email address is john@example.com. My friend's email is mary@example.com."
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
for email in emails:
print(email)
輸出結果:
john@example.com
mary@example.com
在上面的示例中,使用了正則表達式來匹配字符串中的電子郵件地址。re.findall() 函數返回一個列表,包含了所有匹配到的電子郵件地址。然后使用 for 循環遍歷列表,并打印每個電子郵件地址。
丸趣 TV 網 – 提供最優質的資源集合!
正文完