正则替换
正则表达式作用就是用来对字符串进行检索和替换
检索:match、search、fullmatch、finditer、findall
替换:sub
sub
- 语法:
import re
re.sub(参数1,参数2,参数3)
1.参数1:正则规则
2.参数2:作为替换的字符串或者一个函数
3.参数3:被检索字符串
- 案例:
import re
#1、 \d:对于被检索字符串中所有匹配的字符进行替换
print(re.sub(r'\d', '张', '123456'))
#张张张张张张
#2、 \d+:将多个连续被匹配的字符替换成一个参数2的值
print(re.sub(r'\d+', '张', 'abc123d456e'))
#abc张d张e
#3、参数2使用函数替代的用法
p = ’hello34good23‘
def test1(a):
print(a)
#sub 内部在调用test1方法时,会把每个匹配到的数据以re.Match的格式传递给test
re.sub(r'\d',test1,p)
'''
<re.Match object; span=(5, 6), match='3'>
<re.Match object; span=(6, 7), match='4'>
<re.Match object; span=(11, 12), match='2'>
<re.Match object; span=(12, 13), match='3'>
'''
def test(a):
y = int(a.group(0))
y *= 2
return str(y) #因为p变量是个字符串,所以函数返回的值也必须是字符串类型
# 1.sub 内部在调用test方法时,会把每个匹配到的数据以re.Match的格式传递给test
# 2.然后test函数会将该数据进行一定操作后,return返回出来放回到变量p中对应的位置,从而实现不影响字符串中其他字符的值和位置
print(re.sub(r'\d', test, p))
#hello68good46