Python 中的正則表達式
本文講解了 Python 中的正則表達式。
我們將涵蓋多種主題,從 re 模組的基本用法到複雜的正則表達式模式匹配。
YouTube Video
Python 中的正則表達式
re 模組用於使用正則表達式搜索和操作字串。
什麼是 re 模組?
re 模組包含在 Python 的標準庫中,可用於使用正則表達式處理字串。正則表達式用於高效地查找、提取或替換特定的字串模式。
基本的正則表達式模式
正則表達式使用特殊符號定義模式。以下是一些基本模式。
.:任意單一字元^:字串的開頭$:字串的結尾\d:任意數字 (0-9)\w:任意字母字符 (a-z, A-Z, 0-9, _)\s:任意空白字符*:零次或多次重複+:一次或多次重複[]:字符類別(例如,[a-z]匹配小寫字母)
1import re
2
3pattern = r"\d{3}-\d{4}"
4text = "My postal code is 123-4567."
5result = re.search(pattern, text)
6if result:
7 print(result.group()) # Output: 123-4567
8
9# Define a pattern using basic regular expression symbols
10pattern = r"^\w+\s\d+\s[a-zA-Z]+$"
11
12# Example text to test the pattern
13text = "Room 23 Tokyo"
14
15# Check if the pattern matches the text
16result = re.match(pattern, text)
17if result:
18 print("Matched:", result.group())
19else:
20 print("No match")- 此程式碼首先檢查字串是否符合郵遞區號的模式。接著,檢查整個字串(從開頭到結尾)是否符合由單字、空白、數字、空白與英文字所組成的模式。這有助於你瞭解正則表達式的基本元素如何組合在一起。
如何使用匹配函數
re.match()
re.match() 用於檢查字串的開頭是否匹配指定的模式。
1import re
2
3pattern = r"\w+"
4text = "Python is powerful"
5match = re.match(pattern, text)
6if match:
7 print(match.group()) # Output: Python- 此程式碼檢查字串是否以單字字元(字母、數字或底線)開頭。第一個單字 'Python' 符合該模式並被輸出。
re.search()
re.search() 掃描整個字串並返回第一個匹配項。
1import re
2
3pattern = r"powerful"
4text = "Python is powerful and versatile"
5search = re.search(pattern, text)
6if search:
7 print(search.group()) # Output: powerful- 此程式碼在整個字串中搜尋單字 'powerful',並回傳第一個匹配項。因此,
re.search()會輸出匹配到的字串 'powerful'。
re.findall()
re.findall() 將模式的所有匹配返回為列表。
1import re
2
3pattern = r"\b\w{6}\b"
4text = "Python is powerful and versatile"
5matches = re.findall(pattern, text)
6print(matches) # Output: ['Python', 'strong']- 此程式碼尋找所有長度正好為六個字元的單字,並將它們以清單回傳。字串中的 'Python' 符合條件,輸出清單
['Python']。
re.finditer()
re.finditer() 將所有匹配返回為迭代器,讓您能獲取每個匹配的詳細資訊。
1import re
2
3pattern = r"\b\w{6}\b"
4text = "Python is powerful and versatile"
5matches = re.finditer(pattern, text)
6for match in matches:
7 print(match.group()) # Output: Python- 此程式碼依序搜尋所有六個字母的單字,並透過迭代器處理每個匹配項。'Python' 在此處符合該模式並被輸出。
替換與分割
re.sub()
re.sub() 將匹配正則表達式的字串部分替換為其他字串。
1import re
2
3pattern = r"\d+"
4text = "There are 100 apples"
5new_text = re.sub(pattern, "many", text)
6print(new_text) # Output: There are many apples- 此程式碼將字串中的所有數字替換為 'many'。
re.split()
re.split() 在與正則表達式匹配的部分進行分割。
1import re
2
3pattern = r"\s+"
4text = "Python is powerful"
5parts = re.split(pattern, text)
6print(parts) # Output: ['Python', 'is', 'powerful']- 此程式碼按照一個或多個空白字元分割字串。因此,字串被分割為各個單字,得到
['Python', 'is', 'powerful']。
群組與捕獲
使用正則表達式群組可以輕鬆提取匹配的子字串。用括號 () 括住會將其捕獲為一個群組。
1import re
2
3pattern = r"(\d{3})-(\d{4})"
4text = "My postal code is 123-4567."
5match = re.search(pattern, text)
6if match:
7 print(match.group(1)) # Output: 123
8 print(match.group(2)) # Output: 4567- 此程式碼從形如 '123-4567' 的郵遞區號中,將 3 位與 4 位數字分別作為群組擷取出來。
group(1)回傳前三位數字 '123',而group(2)回傳最後四位數字 '4567'。
具名群組
使用具名群組可讓你以有意義的名稱來擷取值,而非依賴索引。以下是一個從日誌中擷取日期與等級的具體範例。
1import re
2
3log = "2025-10-25 14:00:01 [ERROR] Something failed"
4
5pattern = r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) \[(?P<level>[A-Z]+)\] (?P<msg>.*)"
6m = re.search(pattern, log)
7if m:
8 print(m.group("date"), m.group("time"), m.group("level"))
9 print("message:", m.group("msg"))- 此程式碼使用具名群組,從日誌字串中擷取日期、時間、等級與訊息。它透過有意義的名稱而非索引來取得這些值。
使用旗標選項
re 模組提供多種旗標選項來控制搜索行為。
re.IGNORECASE(re.I): 使匹配不區分大小寫的旗標選項。re.MULTILINE(re.M): 允許跨多行匹配的旗標選項。re.DOTALL(re.S): 點.也能匹配換行字元的旗標選項。
1import re
2
3pattern = r"python"
4text = "Python is powerful"
5match = re.search(pattern, text, re.IGNORECASE)
6if match:
7 print(match.group()) # Output: Python- 此程式碼以不區分大小寫的方式搜尋單字 'python'。透過使用
re.IGNORECASE旗標,它也會匹配到 'Python'。
正則表達式物件(re.compile)的優點
使用 re.compile 編譯模式,能更有效率地重複使用並提升可讀性。你也可以在此設定旗標。
以下範例使用已編譯的模式跨多行重複搜尋匹配項。若你經常使用相同的模式,透過 re.compile 將其編譯可提升效能。
1import re
2
3pattern = re.compile(r"User: (\w+), ID: (\d+)")
4text = "User: alice, ID: 1\nUser: bob, ID: 2"
5
6for m in pattern.finditer(text):
7 print(m.groups())- 此程式碼使用已編譯的正則表達式,從多行文字中擷取使用者名稱與 ID。
re.compile在重複使用相同模式時可提升效率,也能讓程式碼更易讀。
應用
例如,考慮一個從文本檔案中提取所有電子郵件地址的腳本。
1import re
2
3pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
4text = "Contact us at info@example.com or support@service.com."
5emails = re.findall(pattern, text)
6print(emails) # Output: ['info@example.com', 'support@service.com']- 此程式碼找出字串中的所有電子郵件地址,並將它們擷取為清單。
結論
re 模組是 Python 中用於字串操作的強大工具。這裡,我們涵蓋了從基礎用法到使用群組和旗標選項的進階正則表達式的廣泛主題。Python 的正則表達式功能非常強大,是文本處理中不可或缺的工具。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。