导入re模块
import re
定义正则表达式模式
pattern_obj = re.compile(pattern)
编译正则表达式模式可以将模式转换为可重复使用的正则表达式对象。例如,要编译上面定义的正则表达式模式,可以使用以下代码:
pattern_obj = re.compile(pattern)
匹配文本模式
使用re模块的search()函数可以搜索文本中是否存在符合指定正则表达式模式的子串。例如,要搜索一个字符串中是否包含数字,可以使用以下代码
text = 'hello world 123'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('Match not found')
替换文本模式
使用re模块的sub()函数可以将文本中符合指定正则表达式模式的部分替换为新的字符串。例如,要将一个字符串中的所有数字替换为“X”,可以使用以下代码:
text = 'hello world 123'
new_text = re.sub(pattern, 'X', text)
print('New text:', new_text)
其中,new_text变量存储了替换后的文本。