python re.sub_正则表达式-python:re.sub的用法

正则表达式-python:re.sub的用法

Python 的 re 模块提供了re.sub用于替换字符串中的匹配项。

语法:

re.sub(pattern, repl, string, count=0, flags=0)

参数:pattern : 正则中的模式字符串。

repl : 替换的字符串,也可为一个函数。

string : 要被查找替换的原始字符串。

count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。

例子:

repl : 为一个函数的用法

repl为函数时,比如下面例子中的normalize_orders(matchobj)和 double(matched),其中函数的参数调用的都是re.Match object。

源码如下:

import re

"""

-1234, A193, B123, C124

You must change it to the following:

A1234,- B193, B123, B124

"""

def normalize_orders(matchobj):

print(matchobj)

if matchobj.group(1) == '-':

return "A"

else:

return "B"

re.sub('([-|A-Z])', normalize_orders, '-1234, A193, B123, C124')

import re

# 将匹配的数字乘以 2

def double(matched):

print('matched: ',matched)

print("matched.group('value'): ",matched.group('value'))

value = int(matched.group('value'))

return str(value * 2)

string = 'A23G4HFD567'

print(re.sub('(?P\d+)', double, string))

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值