一、Python正則表達式基礎
1. 導入模塊
Python通過 re
模塊實現正則表達式功能,需先導入模塊:
import re
2. 核心語法
- 普通字符:直接匹配字面值(如
a
匹配字符a
)。 - 元字符:
\d
:匹配數字(等價于[0-9]
)。\w
:匹配字母、數字、下劃線(等價于[a-zA-Z0-9_]
)。\s
:匹配空白字符(空格、制表符等)。^
和$
:分別匹配字符串開頭和結尾。\b
:單詞邊界(如\bpython\b
匹配獨立單詞python
)。
3. 量詞
*
:匹配0次或多次(如a*
匹配空字符串或多個a
)。+
:匹配1次或多次(如a+
至少匹配一個a
)。?
:匹配0次或1次(如a?
可選a
)。{m,n}
:匹配m到n次(如\d{3,5}
匹配3-5位數字)。
二、常用函數與使用示例
1. 匹配函數
re.match()
:從字符串開頭匹配,返回Match
對象(若匹配失敗則返回None
)。text = "Hello, World!" match = re.match(r"Hello", text) if match:print(match.group()) # 輸出 "Hello"
re.search()
:在整個字符串中搜索第一個匹配項。match = re.search(r"World", text) print(match.group()) # 輸出 "World"
re.findall()
:返回所有匹配的子串列表。matches = re.findall(r"\w+", text) # 輸出 ['Hello', 'World']
2. 替換與分割
re.sub()
:替換匹配內容。new_text = re.sub(r"World", "Python", text) # 輸出 "Hello, Python!"
re.split()
:根據模式分割字符串。parts = re.split(r",", text) # 輸出 ['Hello', ' World!']
3. 編譯正則表達式
預編譯可提升多次調用效率:
pattern = re.compile(r"\b\w{3}\b") # 匹配3位單詞
matches = pattern.findall("The quick brown fox")
三、分組與捕獲
使用 ()
分組提取特定內容:
text = "apple, banana, cherry"
match = re.match(r"(\w+), (\w+), (\w+)", text)
print(match.groups()) # 輸出 ('apple', 'banana', 'cherry')
非貪婪匹配
添加 ?
實現最小匹配:
text = "2023-04-02T10:11:12Z"
date = re.search(r"\d{4}-\d{2}-\d{2}", text).group() # 輸出 "2023-04-02"
四、實際應用場景
1. 數據驗證
- 手機號驗證:
^1[3-9]\d{9}$
(以1開頭,第二位3-9,后接9位數字)。 - 郵箱提取:
([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})
。
2. 文本處理
- 日期格式化:將
20230209
轉為2023.02.09
:text = "管理辦法20230209(修訂).docx" new_text = re.sub(r"(\d{4})(\d{2})(\d{2})", r"\1.\2.\3", text) # 輸出 "管理辦法2023.02.09(修訂).docx"
3. 網頁數據抓取
- 提取鏈接:
import re, requests from bs4 import BeautifulSoup url = "https://example.com" html = requests.get(url).text links = re.findall(r'href\s*=\s*["\']([^"\']+)["\']', html)
五、優化技巧
- 預編譯正則表達式:使用
re.compile()
減少重復編譯開銷。 - 避免過度使用
.*
:優先用精確匹配(如\d{4}
代替.*
)。 - 忽略大小寫:添加
re.IGNORECASE
修飾符(如re.findall(r"python", text, re.I)
)。
六、總結
Python的 re
模塊提供了強大的正則表達式功能,涵蓋匹配、替換、分組等操作。結合預編譯和優化技巧,可高效處理文本數據。實際開發中建議使用在線工具(如 Regexr)調試復雜表達式。