Python中的正則表達式庫re提供了許多高效用法,以下是一些常用的技巧:
re.compile()
預編譯正則表達式模式,可以提高匹配效率。pattern = re.compile(r'\d+')
result = pattern.findall('abc123def456')
re.finditer()
遍歷所有匹配項,而不是一次性返回所有匹配項。pattern = re.compile(r'\d+')
for match in pattern.finditer('abc123def456'):
print(match.group())
re.search()
查找第一個匹配項,而不是返回所有匹配項。pattern = re.compile(r'\d+')
match = pattern.search('abc123def456')
if match:
print(match.group())
re.split()
根據正則表達式模式分割字符串。pattern = re.compile(r'\s+')
result = pattern.split('hello world')
print(result) # 輸出:['', 'hello', 'world', '']
re.sub()
替換字符串中的匹配項。pattern = re.compile(r'\d+')
result = pattern.sub('numbers', 'abc123def456')
print(result) # 輸出:'abcnumbersdefnumbers'
re.findall()
查找所有非重疊匹配項,并返回一個列表。pattern = re.compile(r'\d+')
result = pattern.findall('abc123def456')
print(result) # 輸出:['123', '456']
re.finditer()
查找所有非重疊匹配項,并返回一個迭代器。pattern = re.compile(r'\d+')
for match in pattern.finditer('abc123def456'):
print(match.group())
re.subn()
替換字符串中的匹配項,并返回一個元組,包含替換后的字符串和替換次數。pattern = re.compile(r'\d+')
result = pattern.subn('numbers', 'abc123def456')
print(result) # 輸出:('abcnumbersdefnumbers', 2)
re.escape()
轉義正則表達式中的特殊字符。pattern = re.compile(re.escape('hello.world'))
result = pattern.findall('hello.world')
print(result) # 輸出:['hello.world']
re.IGNORECASE
或re.I
標志進行不區分大小寫的匹配。pattern = re.compile(r'\d+', re.IGNORECASE)
result = pattern.findall('abc123Def456')
print(result) # 輸出:['123', '456']
這些高效用法可以幫助你更有效地使用Python中的正則表達式庫re。