正則表達式是一種強大的工具,可以在文本中搜索、匹配、替換特定的模式。Python的re模塊提供了處理正則表達式的基本方法,使得我們能夠高效地使用正則表達式進行字元串匹配。
一、正則表達式基礎
在使用Python的re模塊之前,我們需要了解正則表達式的基本語法。下面是一些正則表達式的基本元字元:
- . 代表任意單個字元。
- ^ 代表匹配字元串的起始位置。
- $ 代表匹配字元串的終止位置。
- * 代表匹配前一個字元0次或多次。
- + 代表匹配前一個字元1次或多次。
- ? 代表匹配前一個字元0次或1次。
- {m,n} 匹配前一個字元m到n次。
- \ 轉義字元,可以使元字元失去特殊意義。
此外,還有一些特殊的字元類:
- \d 匹配數字。
- \w 匹配字母、數字或下劃線。
- \s 匹配空格、製表符、換行符等空白字元。
我們可以使用這些元字元和字元類來構建正則表達式。比如,下面的正則表達式可以匹配一個Email地址:
import re pattern = r"\w+@\w+\.\w+" result = re.match(pattern, "abc123@gmail.com") if result: print("Match succeeded!") else: print("Match failed!")
上面的代碼輸出Match succeeded!,說明正則表達式成功匹配了字元串abc123@gmail.com。
二、使用re模塊進行字元串匹配
Python的re模塊提供了多個函數來處理正則表達式。下面介紹其中一些常用函數。
1. re.match
re.match函數用於從字元串的起始位置開始匹配。如果成功匹配,返回一個匹配對象;否則返回None。
import re pattern = r"hello" result = re.match(pattern, "hello world") if result: print("Match succeeded!") else: print("Match failed!")
上面的代碼輸出Match succeeded!,說明正則表達式成功匹配了字元串hello。
2. re.search
re.search函數用於在字元串中搜索匹配正則表達式的第一個位置。如果成功匹配,返回一個匹配對象;否則返回None。
import re pattern = r"world" result = re.search(pattern, "hello world") if result: print("Match succeeded!") else: print("Match failed!")
上面的代碼輸出Match succeeded!,說明正則表達式成功匹配了字元串world。
3. re.findall
re.findall函數用於在字元串中搜索匹配正則表達式的所有位置,並返回一個列表。
import re pattern = r"\d+" result = re.findall(pattern, "one12two3three4four56") print(result)
上面的代碼輸出[’12’, ‘3’, ‘4’, ’56’],說明正則表達式成功匹配了所有的數字。
4. re.split
re.split函數用於根據正則表達式來分割字元串,並返回一個列表。
import re pattern = r"\s+" result = re.split(pattern, "hello world") print(result)
上面的代碼輸出[‘hello’, ‘world’],說明正則表達式成功將字元串分割成了兩部分。
5. re.sub
re.sub函數用於根據正則表達式來替換字元串中的匹配項,並返回一個新的字元串。
import re pattern = r"\d+" result = re.sub(pattern, "*", "one12two3three4four56") print(result)
上面的代碼輸出on*two*three*four*,說明正則表達式成功將字元串中的數字替換成了星號。
三、應用實例
1. 匹配URL
下面的正則表達式可以匹配URL:
import re pattern = r"https?://(\w+\.)*\w+\.\w+(/\w*)*" result = re.match(pattern, "http://www.baidu.com") if result: print("Match succeeded!") else: print("Match failed!")
上面的代碼輸出Match succeeded!,說明正則表達式成功匹配了URL http://www.baidu.com。
2. 匹配電話號碼
下面的正則表達式可以匹配中國大陸的電話號碼:
import re pattern = r"1[3-9]\d{9}" result = re.match(pattern, "13912345678") if result: print("Match succeeded!") else: print("Match failed!")
上面的代碼輸出Match succeeded!,說明正則表達式成功匹配了電話號碼13912345678。
3. 拆分HTML文件
下面的代碼可以將HTML文件拆分成多個文本文件:
import re # 讀取HTML文件 with open("index.html", "r") as f: html = f.read() # 拆分HTML文件 parts = re.split(r"", html) # 保存拆分後的文本文件 for i, part in enumerate(parts[1:], start=1): filename = f"part{i}.txt" with open(filename, "w") as f: f.write(part)
上面的代碼將HTML文件中的所有
標籤作為拆分點,將拆分後的文本文件分別保存到part1.txt、part2.txt、part3.txt等文件中。結語
本文介紹了Python正則表達式的基礎知識、re模塊的常用函數以及一些實際應用例子,希望對初學者有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/184859.html