正则表达式(Regular Expression)是一种强大的文本处理工具,它使用特定模式来匹配、查找和替换字符串。在Python中,我们通过内置的re模块来使用正则表达式功能。
Python的re模块提供了多种正则表达式操作方法:
import re
# 匹配字符串
result = re.match(r'\d+', '123abc')
# 搜索字符串
result = re.search(r'\d+', 'abc123def')
# 查找所有匹配
results = re.findall(r'\d+', '123abc456def789')
# 替换字符串
new_str = re.sub(r'\d+', '#', '123abc456def789')
\d - 匹配数字\w - 匹配字母数字下划线\s - 匹配空白字符. - 匹配任意字符(除换行符)* - 匹配前一个字符0次或多次+ - 匹配前一个字符1次或多次? - 匹配前一个字符0次或1次{n} - 匹配前一个字符n次^ - 匹配字符串开头$ - 匹配字符串结尾pattern = r'(\d{3})-(\d{3,8})'
match = re.match(pattern, '010-12345')
if match:
print(match.group(1)) # 010
print(match.group(2)) # 12345
# 贪婪匹配
print(re.match(r'^\d+', '123456').group()) # 123456
# 非贪婪匹配
print(re.match(r'^\d+?', '123456').group()) # 1
pattern = re.compile(r'\d+')
result = pattern.findall('123abc456def789')
re.findall(r'[\u4e00-\u9fa5]+', '你好Python 2023')
re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', 'test@example.com')
re.match(r'https?://[\w\.-]+\.[\w\.-]+(/[\w\.-]*)*', 'https://www.example.com/path')
通过掌握这些正则表达式技巧,你将能够高效处理Python中的各种文本匹配和提取任务。