re.sub借助group替换字符串示例

正则表达式-python:re.sub的用法^[1]^

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(‘(?Pd+)’, double, string))


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!