Python 3正则表达式
Python 3正则表达式是一种文本处理工具,可以用来搜索替换文本中的字符串,从而实现文本处理的任务。它可以帮助开发者更快捷地完成文本处理任务,而不用编写长长的程序代码。
使用方法
Python 3正则表达式的使用方法非常简单,只需要导入re模块,使用re.compile()函数将正则表达式字符串编译成正则表达式对象,就可以使用正则表达式对象的属性和方法来处理文本。
import re # 编译正则表达式 pattern = re.compile(r'\d+') # 使用正则表达式处理文本 result = pattern.findall('hello 123 world 456') # 打印结果 print(result)
示例详解
-
使用正则表达式查找字符串:
import re # 编译正则表达式 pattern = re.compile(r'\d+') # 使用正则表达式查找字符串 result = pattern.findall('hello 123 world 456') # 打印结果 print(result)
结果:['123', '456']
-
使用正则表达式替换字符串:
import re # 编译正则表达式 pattern = re.compile(r'\d+') # 使用正则表达式替换字符串 result = pattern.sub('#', 'hello 123 world 456') # 打印结果 print(result)
结果:hello # world #
-
使用正则表达式分割字符串:
import re # 编译正则表达式 pattern = re.compile(r'\d+') # 使用正则表达式分割字符串 result = pattern.split('hello 123 world 456') # 打印结果 print(result)
结果:['hello ', ' world ', '']