# Python 正則表達式完全指南
正則表達式(Regular Expression)是Python中進行文本處理的強大工具。本指南將詳細介紹Python中正則表達式的使用方法和實踐技巧。
## 1. 基礎知識
### 1.1 導入正則表達式模塊
```python
import re
```
### 1.2 創建正則表達式
在Python中有兩種方式創建正則表達式:
```python
# 方式1:使用原始字符串(推薦)
pattern = r'\d+'
# 方式2:普通字符串(需要額外轉義)
pattern = '\\d+'
```
### 1.3 基本匹配方法
```python
import re
text = "Hello, my phone is 123-456-7890"
# 1. re.match() - 從字符串開始處匹配
result = re.match(r'\w+', text)
print(result.group()) ?# 輸出: Hello
# 2. re.search() - 搜索整個字符串中的第一個匹配
result = re.search(r'\d+', text)
print(result.group()) ?# 輸出: 123
# 3. re.findall() - 找到所有匹配項
result = re.findall(r'\d+', text)
print(result) ?# 輸出: ['123', '456', '7890']
# 4. re.finditer() - 返回迭代器
for match in re.finditer(r'\d+', text):
? ? print(f"Found {match.group()} at position {match.start()}-{match.end()}")
```
## 2. 正則表達式語法
### 2.1 字符匹配
```python
# 示例文本
text = "Python3 is awesome! Price: $99.99"
# 匹配單個字符
re.findall(r'.', text) ? ? ?# 匹配任意字符
re.findall(r'\d', text) ? ? # 匹配數字
re.findall(r'\D', text) ? ? # 匹配非數字
re.findall(r'\w', text) ? ? # 匹配字母/數字/下劃線
re.findall(r'\W', text) ? ? # 匹配非字母/數字/下劃線
re.findall(r'\s', text) ? ? # 匹配空白字符
re.findall(r'\S', text) ? ? # 匹配非空白字符
```
### 2.2 數量詞
```python
# 文本示例
text = "Python programming is fun!!!"
# 常用數量詞
re.search(r'o*', text) ? ? ?# 匹配0次或多次
re.search(r'o+', text) ? ? ?# 匹配1次或多次
re.search(r'o?', text) ? ? ?# 匹配0次或1次
re.search(r'o{2}', text) ? ?# 精確匹配2次
re.search(r'o{1,3}', text) ?# 匹配1到3次
```
### 2.3 字符類
```python
text = "The quick brown fox jumps over the lazy dog."
# 使用字符類
re.findall(r'[aeiou]', text) ? ?# 匹配所有元音字母
re.findall(r'[^aeiou]', text) ? # 匹配所有非元音字母
re.findall(r'[a-z]', text) ? ? ?# 匹配所有小寫字母
re.findall(r'[A-Z]', text) ? ? ?# 匹配所有大寫字母
```
## 3. 高級特性
### 3.1 分組和捕獲
```python
# 分組示例
text = "John Smith, Jane Doe, Bob Johnson"
# 基本分組
pattern = r'(\w+)\s(\w+)'
matches = re.findall(pattern, text)
print(matches) ?# 輸出: [('John', 'Smith'), ('Jane', 'Doe'), ('Bob', 'Johnson')]
# 命名分組
pattern = r'(?P<first>\w+)\s(?P<last>\w+)'
for match in re.finditer(pattern, text):
? ? print(f"First: {match.group('first')}, Last: {match.group('last')}")
```
### 3.2 前向查找和后向查找
```python
text = "Price: $100, Cost: $50"
# 正向前向查找
re.findall(r'\d+(?=\s*dollars)', text) ?# 匹配后面跟著"dollars"的數字
# 負向前向查找
re.findall(r'\d+(?!\s*dollars)', text) ?# 匹配后面不跟"dollars"的數字
# 正向后向查找
re.findall(r'(?<=\$)\d+', text) ?# 匹配前面有$的數字
# 負向后向查找
re.findall(r'(?<!\$)\d+', text) ?# 匹配前面沒有$的數字
```
## 4. 實用示例
### 4.1 數據驗證
```python
def validate_email(email):
? ? """驗證電子郵件地址"""
? ? pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
? ? return bool(re.match(pattern, email))
def validate_phone(phone):
? ? """驗證中國手機號"""
? ? pattern = r'^1[3-9]\d{9}$'
? ? return bool(re.match(pattern, phone))
def validate_password(password):
? ? """驗證密碼強度(至少8位,包含大小寫字母和數字)"""
? ? pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$'
? ? return bool(re.match(pattern, password))
```
### 4.2 文本處理
```python
def extract_urls(text):
? ? """提取文本中的URL"""
? ? pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
? ? return re.findall(pattern, text)
def clean_text(text):
? ? """清理文本(刪除多余空白字符)"""
? ? return re.sub(r'\s+', ' ', text).strip()
def extract_dates(text):
? ? """提取日期(支持多種格式)"""
? ? pattern = r'\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2}[-/]\d{4}'
? ? return re.findall(pattern, text)
```
## 5. 性能優化技巧
### 5.1 編譯正則表達式
```python
# 當需要多次使用同一個正則表達式時,應該編譯它
pattern = re.compile(r'\d+')
# 使用編譯后的正則表達式
text = "123 456 789"
matches = pattern.findall(text)
```
### 5.2 優化技巧
1. 使用非捕獲組 `(?:)`:當不需要捕獲結果時
```python
# 不好的寫法
pattern = r'(https?://)(.*)'
# 好的寫法
pattern = r'(?:https?://)(.*)'
```
2. 避免過度使用通配符
```python
# 不好的寫法
pattern = r'.*foo.*'
# 好的寫法
pattern = r'[^/]*foo[^/]*'
```
## 6. 常見問題和解決方案
### 6.1 貪婪vs非貪婪匹配
```python
text = "<p>First</p><p>Second</p>"
# 貪婪匹配(默認)
re.findall(r'<p>.*</p>', text) ?# 匹配整個字符串
# 非貪婪匹配
re.findall(r'<p>.*?</p>', text) ?# 分別匹配每個標簽
```
### 6.2 處理特殊字符
```python
# 轉義特殊字符
def escape_special_chars(text):
? ? return re.escape(text)
# 示例
pattern = re.escape('hello.world') ?# 將點號轉義
```
## 7. 調試技巧
```python
# 使用verbose模式使正則表達式更易讀
pattern = re.compile(r"""
? ? \d+ ? ? ? ? ?# 匹配數字
? ? \s* ? ? ? ? ?# 可選的空白字符
? ? [a-zA-Z]+ ? ?# 匹配字母
? ? """, re.VERBOSE)
# 使用re.DEBUG標志查看編譯信息
pattern = re.compile(r'\d+\s*[a-zA-Z]+', re.DEBUG)
```
## 總結
Python的正則表達式功能強大且靈活,掌握它可以大大提高文本處理效率。關鍵點:
1. 合理使用原始字符串(r'')
2. 需要重復使用時記得編譯正則表達式
3. 注意貪婪vs非貪婪匹配
4. 適當使用命名分組提高代碼可讀性
5. 考慮性能優化
6. 編寫復雜正則表達式時使用verbose模式
記住:編寫正則表達式時應該遵循"簡單夠用"的原則,過于復雜的正則表達式往往會帶來維護困難和性能問題。