Python 正規表達式(Regular Expressions)入門 | Python
2026/04/30
正規表達式(Regular Expressions)是一種強大的文字匹配工具,幾乎所有程式語言都支援。Python 透過內建的 re 模組提供完整的正規表達式功能,讓你能夠高效地進行文字搜尋、比對與替換。
什麼是正規表達式?
正規表達式(Regular Expression,簡稱 Regex)是一種用特殊符號組成的「模式字串」,用來描述文字的匹配規則。例如,\d{3}-\d{4} 可以匹配像 123-4567 這樣的電話號碼格式。在 Python 中,使用 re 模組來操作正規表達式:
import re
撰寫正規表達式時,建議使用原始字串(Raw String)r"..." 來避免反斜線的轉義問題。
基本匹配模式
以下是最常用的正規表達式符號:
| 符號 | 說明 | 範例 |
|---|---|---|
. | 任意一個字元 | a.c 匹配 abc、a1c |
\d | 數字(0-9) | \d+ 匹配 123 |
\w | 文字字元(字母、數字、底線) | \w+ 匹配 hello_1 |
\s | 空白字元 | \s+ 匹配空格、Tab |
* | 前一個字元出現 0 次以上 | ab*c 匹配 ac、abc、abbc |
+ | 前一個字元出現 1 次以上 | ab+c 匹配 abc、abbc |
? | 前一個字元出現 0 或 1 次 | colou?r 匹配 color、colour |
^ | 字串開頭 | ^Hello 匹配開頭的 Hello |
$ | 字串結尾 | end$ 匹配結尾的 end |
[] | 字元集合 | [aeiou] 匹配任一母音 |
re.match() 與 re.search()
re.match() 只從字串開頭匹配,而 re.search() 會搜尋整個字串中第一個符合的位置:
import re
text = "Hello Python World"
# match() 只從開頭匹配
result = re.match(r"Hello", text)
print(result.group()) # 輸出:Hello
# match() 找不到非開頭的內容
result = re.match(r"Python", text)
print(result) # 輸出:None
# search() 搜尋整個字串
result = re.search(r"Python", text)
print(result.group()) # 輸出:Python
re.findall():找出所有匹配
re.findall() 會回傳所有符合模式的字串列表:
import re
text = "我的電話是 02-1234-5678,手機是 0912-345-678"
# 找出所有數字
numbers = re.findall(r"\d+", text)
print(numbers)
# 輸出:['02', '1234', '5678', '0912', '345', '678']
# 找出所有電話格式(數字-數字-數字)
phones = re.findall(r"\d{2,4}-\d{3,4}-\d{3,4}", text)
print(phones)
# 輸出:['02-1234-5678', '0912-345-678']
re.sub():搜尋與替換
re.sub() 可以將符合模式的部分替換為指定的字串:
import re
text = "今天是 2026-04-24,明天是 2026-04-25"
# 將日期格式從 YYYY-MM-DD 改為 YYYY/MM/DD
result = re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\1/\2/\3", text)
print(result)
# 輸出:今天是 2026/04/24,明天是 2026/04/25
# 隱藏手機號碼中間四碼
phone = "0912-345-678"
hidden = re.sub(r"(\d{4})-\d{3}-(\d{3})", r"\1-***-\2", phone)
print(hidden)
# 輸出:0912-***-678
群組(Groups):擷取匹配的部分
使用小括號 () 可以在模式中建立群組,方便擷取特定部分:
import re
text = "姓名:王小明,年齡:25,信箱:ming@example.com"
# 擷取信箱的使用者名稱和網域
match = re.search(r"(\w+)@(\w+\.\w+)", text)
if match:
print(f"完整信箱:{match.group()}") # 輸出:ming@example.com
print(f"使用者名稱:{match.group(1)}") # 輸出:ming
print(f"網域:{match.group(2)}") # 輸出:example.com
re.compile():編譯正規表達式
當同一個模式需要重複使用時,可以用 re.compile() 預先編譯,提升效能:
import re
# 編譯 Email 驗證模式
email_pattern = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
emails = [
"user@example.com",
"invalid-email",
"test.name@company.org",
"not@valid",
]
for email in emails:
if email_pattern.match(email):
print(f"有效:{email}")
else:
print(f"無效:{email}")
# 輸出:
# 有效:user@example.com
# 無效:invalid-email
# 有效:test.name@company.org
# 無效:not@valid
常用旗標(Flags)
re 模組提供了幾個實用的旗標來調整匹配行為:
import re
# re.IGNORECASE — 忽略大小寫
result = re.findall(r"python", "Python PYTHON python", re.IGNORECASE)
print(result)
# 輸出:['Python', 'PYTHON', 'python']
# re.MULTILINE — 讓 ^ 和 $ 匹配每一行的開頭和結尾
text = "第一行\n第二行\n第三行"
result = re.findall(r"^第.行", text, re.MULTILINE)
print(result)
# 輸出:['第一行', '第二行', '第三行']
總結
正規表達式是文字處理中不可或缺的工具。本文介紹了 Python re 模組的核心函式:match()(開頭匹配)、search()(全文搜尋)、findall()(找出所有匹配)、sub()(搜尋替換),以及群組擷取、compile() 編譯和常用旗標。掌握這些基礎後,你就能靈活地處理各種文字搜尋與驗證的需求。希望這篇文章能幫助你踏出正規表達式的第一步。
如果你想複習 Python 字串的基本操作,請參考 Python 字串格式化教學。
關於模組與套件的匯入方式,請閱讀 Python 模組與套件教學。