Python正則表達式:十個正則表達式應用實例
正則表達式,常被稱為“regex”,是處理文本數(shù)據(jù)的超級工具。在Python中,通過re模塊,我們可以輕松地進行模式匹配、搜索、替換等操作。本文將通過15個實例,從基礎到進階,讓你掌握Python正則表達式的實用技巧。
實例1:基本匹配
目標:找出字符串中的所有單詞。
import re
text = "Hello, world! Welcome to Python programming."
words = re.findall(r'\b\w+\b', text)
print(words) # 輸出: ['Hello', 'world', 'Welcome', 'to', 'Python', 'programming']
解釋:\b表示單詞邊界,\w+匹配一個或多個字母數(shù)字字符。
實例2:數(shù)字提取
目標:提取電話號碼(假設格式為XXX-XXXX-XXXX)。
phone_numbers = "My number is 123-456-7890."
matches = re.findall(r'\d{3}-\d{4}-\d{4}', phone_numbers)
print(matches) # 輸出: ['123-456-7890']
技巧:\d代表數(shù)字,{n}指定重復次數(shù)。
實例3:郵箱地址匹配
目標:從一段文本中找出所有郵箱地址。
text_email = "Contact us at info@example.com or support@example.co.uk."
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text_email)
print(emails) # 輸出: ['info@example.com', 'support@example.co.uk']
注意:郵箱地址的正則表達式相對復雜,但能匹配大多數(shù)格式。
實例4:替換操作
目標:將所有的“Python”替換為“Python編程”。
text_replace = "Python is fun. I love Python."
updated_text = re.sub(r'Python', 'Python編程', text_replace)
print(updated_text) # 輸出: Python編程 is fun. I love Python編程.
功能:re.sub()用于替換匹配到的內(nèi)容。
實例5:貪婪與非貪婪匹配
目標:提取HTML標簽間的文本,考慮非貪婪匹配。
html_text = "<p>Hello, world!</p><div>Welcome!</div>"
content = re.findall(r'<[^>]*>(.*?)</[^>]*>', html_text, re.DOTALL)
print(content) # 輸出: ['Hello, world!', 'Welcome!']
關鍵:?使匹配非貪婪,re.DOTALL使.匹配包括換行在內(nèi)的所有字符。
實例6:分組與引用
目標:提取網(wǎng)址的協(xié)議和主機部分。
url = "https://www.example.com/path"
protocol, host = re.search(r'^(https?://)([^/]+)', url).groups()
print(protocol, host) # 輸出: https:// www.example.com
解析:圓括號定義了分組,\1和\2引用分組內(nèi)容。
實例7:重復模式
目標:匹配連續(xù)的數(shù)字序列。
sequence = "123456789012345"
consecutive_digits = re.findall(r'(\d)\1+', sequence)
print(consecutive_digits) # 輸出: ['1', '2', '3', '4', '5']
技巧:\1+匹配至少一次前面的分組。
實例8:否定預查
目標:查找不以數(shù)字開頭的單詞。
text = "3 apples, no bananas, 10 oranges."
words = re.findall(r'\b(?!\d)\w+\b', text)
print(words) # 輸出: ['apples,', 'no', 'bananas,', 'oranges.']
解釋:(?!...)是負向前瞻,確保其后不匹配特定模式。
實例9:條件匹配
目標:區(qū)分郵箱的教育和商業(yè)賬號。
email_text = "edu@example.edu biz@example.biz"
edu_or_biz = re.findall(r'(\w+@)(edu|biz)\.', email_text)
print(edu_or_biz) # 輸出: [('edu@example.', 'edu'), ('biz@example.', 'biz')]
使用:通過條件分支實現(xiàn)特定匹配。
實例10:全局標志
目標:大小寫不敏感的搜索。
mixed_case = "Python is fun. PYTHON too!"
result = re.findall(r'python', mixed_case, re.IGNORECASE)
print(result) # 輸出: ['Python', 'PYTHON']
標志:re.IGNORECASE忽略大小寫。
實戰(zhàn)案例:清理CSV文件中的無效數(shù)據(jù)
場景:從CSV文件中移除非數(shù)字的手機號碼記錄。
import csv
import re
# 假設手機號碼應為10位數(shù)字
pattern = re.compile(r'^\d{10}$')
with open('phone_numbers.csv', 'r') as file:
reader = csv.reader(file)
cleaned_data = []
for row in reader:
if pattern.match(row[0]): # 假設手機號碼在第一列
cleaned_data.append(row)
# 將清洗后的數(shù)據(jù)保存到新文件
with open('cleaned_phone_numbers.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(cleaned_data)
分析:此案例展示了如何結合正則表達式和文件操作來處理實際問題,確保數(shù)據(jù)質(zhì)量。
通過上述實例和實戰(zhàn)案例,你已經(jīng)掌握了Python正則表達式的基礎到進階應用。