Python中的re模块提供了正则表达式相关的功能,它允许使用正则表达式来搜索、匹配和操作字符串。下面是一些常见的re模块的功能和用法
导入re模块:
import re
匹配字符串:
pattern = re.compile(r'\d+') # 匹配一个或多个数字
match = pattern.match('123abc')
if match:
print(match.group()) # 输出:123
搜索字符串:
pattern = re.compile(r'\d+')
matches = pattern.findall('abc123def456')
print(matches) # 输出:['123', '456']
使用正则表达式进行替换:
text = 'hello world'
new_text = re.sub('world', 'Python', text)
print(new_text) # 输出:hello Python
分组和捕获:
pattern = re.compile(r'(\d+) (\w+)') # 匹配数字和单词,并捕获它们
match = pattern.match('123 abc')
if match:
print(match.group(1)) # 输出:123
print(match.group(2)) # 输出:abc
这只是re模块的一些基本用法,它还提供了许多其他功能,如正则表达式的特殊字符、量词、贪婪模式和非贪婪模式等。你可以参考Python官方文档或其他教程来了解更多关于re模块的详细信息和用法。