Python正則表達式匹配和替換的操作指南
基礎語法
導入re模塊
import re
基本元字符
.- 匹配任意字符(除了換行符)\d- 匹配數(shù)字\w- 匹配字母、數(shù)字、下劃線\s- 匹配空白字符[]- 字符集*- 0次或多次+- 1次或多次?- 0次或1次{n}- 恰好n次{n,}- 至少n次{n,m}- n到m次
常用匹配方法
1. re.match() - 從字符串開頭匹配
text = "Hello World 2024"
result = re.match(r"Hello", text)
if result:
print("匹配成功:", result.group()) # 輸出: Hello
2. re.search() - 搜索整個字符串
text = "The year is 2024"
result = re.search(r"\d{4}", text)
if result:
print("找到數(shù)字:", result.group()) # 輸出: 2024
3. re.findall() - 查找所有匹配項
text = "蘋果10元, 香蕉5元, 橙子8元" prices = re.findall(r"\d+元", text) print(prices) # 輸出: ['10元', '5元', '8元']
4. re.finditer() - 返回迭代器
text = "聯(lián)系: 123-4567, 987-6543"
for match in re.finditer(r"\d{3}-\d{4}", text):
print(f"找到電話: {match.group()} 位置: {match.span()}")
替換方法詳解
re.sub() 基本用法
text = "今天是2023年12月15日" # 將年份替換為2024 new_text = re.sub(r"2023", "2024", text) print(new_text) # 輸出: 今天是2024年12月15日
使用分組和引用
text = "張三 李四 王五" # 交換姓和名的位置 new_text = re.sub(r"(\w+) (\w+)", r"\2 \1", text) print(new_text) # 輸出: 李四 張三 王五
使用函數(shù)進行復雜替換
def double_number(match):
number = int(match.group())
return str(number * 2)
text = "數(shù)字: 5, 10, 15"
new_text = re.sub(r"\d+", double_number, text)
print(new_text) # 輸出: 數(shù)字: 10, 20, 30
實際應用案例
案例1:格式化電話號碼
def format_phone_number(text):
# 將各種格式的電話號碼統(tǒng)一為: (xxx) xxx-xxxx
pattern = r"(\d{3})[-.\s]?(\d{3})[-.\s]?(\d{4})"
replacement = r"(\1) \2-\3"
return re.sub(pattern, replacement, text)
phone_text = "聯(lián)系: 123-456-7890, 123.456.7890, 123 456 7890"
formatted = format_phone_number(phone_text)
print(formatted)
# 輸出: 聯(lián)系: (123) 456-7890, (123) 456-7890, (123) 456-7890
案例2:清理HTML標簽
def remove_html_tags(text):
# 移除HTML標簽,保留文本內(nèi)容
return re.sub(r"<[^>]+>", "", text)
html_text = "<h1>標題</h1><p>這是一個<strong>段落</strong></p>"
clean_text = remove_html_tags(html_text)
print(clean_text) # 輸出: 標題這是一個段落
案例3:數(shù)據(jù)脫敏
def mask_sensitive_data(text):
# 隱藏身份證號中間部分
text = re.sub(r"(\d{4})\d{8}(\d{4})", r"\1********\2", text)
# 隱藏手機號中間部分
text = re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", text)
return text
sensitive_text = "身份證: 510123199001011234, 手機: 13800138000"
masked_text = mask_sensitive_data(sensitive_text)
print(masked_text)
# 輸出: 身份證: 5101********1234, 手機: 138****8000
案例4:Salesforce Flow版本更新
import re
def update_flow_version(rows, flow_name, old_version, new_version):
"""
更新Salesforce Flow的多語言鍵名版本號
"""
updated_rows = []
for row in rows:
if row and len(row) >= 1:
key = row[0]
if key and isinstance(key, str):
patterns = [
(f"Flow\.Flow\.{flow_name}\.{old_version}\.",
f"Flow.Flow.{flow_name}.{new_version}."),
(f"Flow\.AutoLaunchedFlow\.{flow_name}\.{old_version}\.",
f"Flow.AutoLaunchedFlow.{flow_name}.{new_version}."),
]
new_key = key
for pattern, replacement in patterns:
if re.search(pattern, key):
new_key = re.sub(pattern, replacement, key)
break
# 更新行的第一個元素
updated_row = list(row)
updated_row[0] = new_key
updated_rows.append(updated_row)
else:
updated_rows.append(row)
else:
updated_rows.append(row)
return updated_rows
# 使用示例
rows = [
["Flow.Flow.CustomerOnboarding.1.title", "客戶入駐流程"],
["Flow.AutoLaunchedFlow.CustomerOnboarding.1.description", "自動啟動流程"],
["Other.Key", "其他值"]
]
updated = update_flow_version(rows, "CustomerOnboarding", "1", "2")
for row in updated:
print(row)
# 輸出:
# ['Flow.Flow.CustomerOnboarding.2.title', '客戶入駐流程']
# ['Flow.AutoLaunchedFlow.CustomerOnboarding.2.description', '自動啟動流程']
# ['Other.Key', '其他值']
案例5:日志文件處理
def parse_log_file(log_content):
"""
解析日志文件,提取時間戳、級別和消息
"""
log_pattern = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) [(\w+)] (.+)"
logs = []
for line in log_content.split('\n'):
match = re.match(log_pattern, line)
if match:
timestamp, level, message = match.groups()
logs.append({
'timestamp': timestamp,
'level': level,
'message': message
})
return logs
# 示例日志內(nèi)容
log_content = """2024-01-15 10:30:25 [INFO] 用戶登錄成功
2024-01-15 10:31:10 [ERROR] 數(shù)據(jù)庫連接失敗
2024-01-15 10:32:45 [WARNING] 內(nèi)存使用率過高"""
parsed_logs = parse_log_file(log_content)
for log in parsed_logs:
print(f"{log['timestamp']} - {log['level']}: {log['message']}")
高級技巧
1. 編譯正則表達式(提高性能)
# 對于需要多次使用的模式,先編譯
phone_pattern = re.compile(r"(\d{3})-(\d{3})-(\d{4})")
texts = ["123-456-7890", "987-654-3210"]
for text in texts:
match = phone_pattern.search(text)
if match:
print(f"完整匹配: {match.group()}, 分組: {match.groups()}")
2. 使用命名分組
text = "日期: 2024-01-15"
pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
match = re.search(pattern, text)
if match:
print(f"年: {match.group('year')}, 月: {match.group('month')}, 日: {match.group('day')}")
3. 非貪婪匹配
text = "<div>內(nèi)容1</div><div>內(nèi)容2</div>"
# 貪婪匹配
greedy = re.findall(r"<div>(.*)</div>", text)
print("貪婪匹配:", greedy) # 輸出: ['內(nèi)容1</div><div>內(nèi)容2']
# 非貪婪匹配
non_greedy = re.findall(r"<div>(.*?)</div>", text)
print("非貪婪匹配:", non_greedy) # 輸出: ['內(nèi)容1', '內(nèi)容2']
4. 前后查找
text = "價格: $100, 折扣: $20"
# 查找$后面的數(shù)字
prices = re.findall(r"(?<=$)\d+", text)
print("價格:", prices) # 輸出: ['100', '20']
最佳實踐
- 使用原始字符串:
r"pattern"避免轉(zhuǎn)義問題 - 編譯常用模式:提高性能
- 合理使用分組:使代碼更清晰
- 處理異常情況:確保匹配失敗時不會崩潰
- 測試正則表達式:使用在線工具驗證模式
總結(jié)
正則表達式是Python中處理文本的強大工具,re.sub()函數(shù)特別適用于字符串替換任務。通過掌握基本語法和高級技巧,你可以高效地處理各種文本處理需求,從簡單的字符串替換到復雜的數(shù)據(jù)提取和格式化。
記住:正則表達式雖然強大,但也要適度使用,對于簡單的字符串操作,Python內(nèi)置的字符串方法可能更合適。
以上就是Python正則表達式匹配和替換的操作指南的詳細內(nèi)容,更多關(guān)于Python正則表達式匹配和替換的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python入門學習關(guān)于for else的特殊特性講解
本文將介紹 Python 中的" for-else"特性,并通過簡單的示例說明如何正確使用它,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
使用Python的package機制如何簡化utils包設計詳解
這篇文章主要給大家介紹了關(guān)于使用Python的package機制如何簡化utils包設計的相關(guān)資料,文中通過示例代碼的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-12-12
Python 圖像處理之顏色遷移(reinhard VS welsh)
這篇文章主要介紹了分別利用reinhard算法和welsh算法實現(xiàn)圖像的顏色遷移,并對二者算法的效果進行了對比,感興趣的小伙伴可以了解一下2021-12-12
Python+Tkinter實現(xiàn)軟件自動更新與提醒
這篇文章主要為大家詳細介紹了Python如何利用Tkinter編寫一個軟件自動更新與提醒小程序,文中的示例代碼簡潔易懂,感興趣的小伙伴可以動手嘗試一下2023-07-07

