Последняя активность 9 months ago

re 模組提供強大的正規表示式功能,可用於文字搜尋、字串處理與資料驗證,適用於日誌分析、表單驗證與文字解析等場景。

re_example.py Исходник
1import re
2
3# 定義正規表示式模式
4pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
5
6# 測試字串
7text = "聯絡我們: support@example.com 或 visit@example.org"
8
9# 搜尋第一個匹配的電子郵件
10match = re.search(pattern, text)
11if match:
12 print(f"找到電子郵件: {match.group()}")
13
14# 找出所有匹配的電子郵件
15matches = re.findall(pattern, text)
16print(f"所有找到的電子郵件: {matches}")
17
18# 取代電子郵件為 [隱藏]
19masked_text = re.sub(pattern, "[隱藏]", text)
20print(f"隱藏處理後的文字: {masked_text}")
21