Python 的 re
模塊提供了多種方法來處理正則表達式。以下是一些常用的方法及其功能介紹:
1. re.match()
在字符串的開始位置進行匹配。
import repattern = r'\d+'
string = "123abc456"match = re.match(pattern, string)
if match:print(f"匹配的字符串是: '{match.group()}'")
2. re.search()
在整個字符串中搜索模式的首次出現。
import repattern = r'\d+'
string = "abc123def456"match = re.search(pattern, string)
if match:print(f"匹配的字符串是: '{match.group()}'")
3. re.findall()
返回所有非重疊的匹配,以列表形式返回。
import repattern = r'\d+'
string = "abc123def456ghi789"matches = re.findall(pattern, string)
print(f"所有匹配項: {matches}")
4. re.finditer()
返回所有非重疊的匹配,以迭代器形式返回每個匹配的 MatchObject
。
import repattern = r'\d+'
string = "abc123def456ghi789"matches = re.finditer(pattern, string)
for match in matches:print(f"匹配的字符串是: '{match.group()}'")
5. re.sub()
使用指定的替換內容,替換所有匹配的子字符串。
import repattern = r'\d+'
string = "abc123def456ghi789"
replacement = '#'result = re.sub(pattern, replacement, string)
print(f"替換后的字符串: '{result}'")
6. re.subn()
與 re.sub()
類似,但返回一個包含新字符串和替換次數的元組。
import repattern = r'\d+'
string = "abc123def456ghi789"
replacement = '#'result, num_subs = re.subn(pattern, replacement, string)
print(f"替換后的字符串: '{result}'")
print(f"替換次數: {num_subs}")
7. re.split()
根據正則表達式模式分割字符串,返回一個列表。
import repattern = r'\d+'
string = "abc123def456ghi789"result = re.split(pattern, string)
print(f"分割結果: {result}")
8. re.compile()
預編譯一個正則表達式模式,可以提高重復使用該模式的效率。
import repattern = re.compile(r'\d+')
string = "abc123def456ghi789"match = pattern.search(string)
if match:print(f"匹配的字符串是: '{match.group()}'")
9. re.escape()
對字符串中所有可能被解釋為正則表達式特殊字符的字符進行轉義。
import restring = "example.abc*123"escaped_string = re.escape(string)
print(f"轉義后的字符串: '{escaped_string}'")