Python正則表達(dá)式匹配和替換的操作指南
基礎(chǔ)語(yǔ)法
導(dǎo)入re模塊
import re
基本元字符
.- 匹配任意字符(除了換行符)\d- 匹配數(shù)字\w- 匹配字母、數(shù)字、下劃線\s- 匹配空白字符[]- 字符集*- 0次或多次+- 1次或多次?- 0次或1次{n}- 恰好n次{n,}- 至少n次{n,m}- n到m次
常用匹配方法
1. re.match() - 從字符串開(kāi)頭匹配
text = "Hello World 2024"
result = re.match(r"Hello", text)
if result:
print("匹配成功:", result.group()) # 輸出: Hello
2. re.search() - 搜索整個(gè)字符串
text = "The year is 2024"
result = re.search(r"\d{4}", text)
if result:
print("找到數(shù)字:", result.group()) # 輸出: 2024
3. re.findall() - 查找所有匹配項(xiàng)
text = "蘋(píng)果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ù)進(jìn)行復(fù)雜替換
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
實(shí)際應(yīng)用案例
案例1:格式化電話號(hào)碼
def format_phone_number(text):
# 將各種格式的電話號(hào)碼統(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標(biāo)簽
def remove_html_tags(text):
# 移除HTML標(biāo)簽,保留文本內(nèi)容
return re.sub(r"<[^>]+>", "", text)
html_text = "<h1>標(biāo)題</h1><p>這是一個(gè)<strong>段落</strong></p>"
clean_text = remove_html_tags(html_text)
print(clean_text) # 輸出: 標(biāo)題這是一個(gè)段落
案例3:數(shù)據(jù)脫敏
def mask_sensitive_data(text):
# 隱藏身份證號(hào)中間部分
text = re.sub(r"(\d{4})\d{8}(\d{4})", r"\1********\2", text)
# 隱藏手機(jī)號(hào)中間部分
text = re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", text)
return text
sensitive_text = "身份證: 510123199001011234, 手機(jī): 13800138000"
masked_text = mask_sensitive_data(sensitive_text)
print(masked_text)
# 輸出: 身份證: 5101********1234, 手機(jī): 138****8000
案例4:Salesforce Flow版本更新
import re
def update_flow_version(rows, flow_name, old_version, new_version):
"""
更新Salesforce Flow的多語(yǔ)言鍵名版本號(hào)
"""
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
# 更新行的第一個(gè)元素
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", "自動(dòng)啟動(dòng)流程"],
["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', '自動(dòng)啟動(dòng)流程']
# ['Other.Key', '其他值']
案例5:日志文件處理
def parse_log_file(log_content):
"""
解析日志文件,提取時(shí)間戳、級(jí)別和消息
"""
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ù)庫(kù)連接失敗
2024-01-15 10:32:45 [WARNING] 內(nèi)存使用率過(guò)高"""
parsed_logs = parse_log_file(log_content)
for log in parsed_logs:
print(f"{log['timestamp']} - {log['level']}: {log['message']}")
高級(jí)技巧
1. 編譯正則表達(dá)式(提高性能)
# 對(duì)于需要多次使用的模式,先編譯
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 = "價(jià)格: $100, 折扣: $20"
# 查找$后面的數(shù)字
prices = re.findall(r"(?<=$)\d+", text)
print("價(jià)格:", prices) # 輸出: ['100', '20']
最佳實(shí)踐
- 使用原始字符串:
r"pattern"避免轉(zhuǎn)義問(wèn)題 - 編譯常用模式:提高性能
- 合理使用分組:使代碼更清晰
- 處理異常情況:確保匹配失敗時(shí)不會(huì)崩潰
- 測(cè)試正則表達(dá)式:使用在線工具驗(yàn)證模式
總結(jié)
正則表達(dá)式是Python中處理文本的強(qiáng)大工具,re.sub()函數(shù)特別適用于字符串替換任務(wù)。通過(guò)掌握基本語(yǔ)法和高級(jí)技巧,你可以高效地處理各種文本處理需求,從簡(jiǎn)單的字符串替換到復(fù)雜的數(shù)據(jù)提取和格式化。
記?。赫齽t表達(dá)式雖然強(qiáng)大,但也要適度使用,對(duì)于簡(jiǎn)單的字符串操作,Python內(nèi)置的字符串方法可能更合適。
以上就是Python正則表達(dá)式匹配和替換的操作指南的詳細(xì)內(nèi)容,更多關(guān)于Python正則表達(dá)式匹配和替換的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
樹(shù)莓派使用python-librtmp實(shí)現(xiàn)rtmp推流h264的方法
今天小編就為大家分享一篇樹(shù)莓派使用python-librtmp實(shí)現(xiàn)rtmp推流h264的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
django ListView的使用 ListView中獲取url中的參數(shù)值方式
這篇文章主要介紹了django ListView的使用 ListView中獲取url中的參數(shù)值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
Python練習(xí)之操作SQLite數(shù)據(jù)庫(kù)
這篇文章主要介紹了Python練習(xí)之操作SQLite數(shù)據(jù)庫(kù),主要通過(guò)三個(gè)問(wèn)題如何創(chuàng)建SQLite數(shù)據(jù)庫(kù)?如何向SQLite表中插入數(shù)據(jù)?如何查詢SQLite表中的數(shù)據(jù)?展開(kāi)文章主題詳情,需要的朋友可以參考一下2022-06-06
python機(jī)器學(xué)習(xí)GCN圖卷積神經(jīng)網(wǎng)絡(luò)原理解析
這篇文章主要為大家介紹了GCN圖卷積神經(jīng)網(wǎng)絡(luò)原理及代碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python 判斷 有向圖 是否有環(huán)的實(shí)例講解
下面小編就為大家分享一篇Python 判斷 有向圖 是否有環(huán)的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02

