Yuh*_*ang 4 python regex backreference function
说我有以下字符串:
old_string = "I love the number 3 so much"
Run Code Online (Sandbox Code Playgroud)
我想发现整数(在上面的例子中,只有一个数字3),并用一个大于1的值替换它们,即,期望的结果应该是
new_string = "I love the number 4 so much"
Run Code Online (Sandbox Code Playgroud)
在Python中,我可以使用:
r = re.compile(r'([0-9])+')
new_string = r.sub(r'\19', s)
Run Code Online (Sandbox Code Playgroud)
9在匹配的整数数字的末尾追加一个.但是,我想申请更一般的内容\1.
如果我定义一个函数:
def f(i):
return i + 1
Run Code Online (Sandbox Code Playgroud)
我该如何申请f()上\1,这样我可以在更换匹配的字符串old_string喜欢的东西f(\1)?
除了具有替换字符串之外,还re.sub允许您使用函数来执行替换:
>>> import re
>>> old_string = "I love the number 3 so much"
>>> def f(match):
... return str(int(match.group(1)) + 1)
...
>>> re.sub('([0-9])+', f, old_string)
'I love the number 4 so much'
>>>
Run Code Online (Sandbox Code Playgroud)
来自文档:
re.sub(pattern, repl, string, count=0, flags=0)If
repl是一个函数,它会在每次非重叠的情况下被调用pattern.该函数接受单个匹配对象参数,并返回替换字符串.