python - 如何在反向引用上应用函数?

标签 python regex function backreference

<分区>

假设我有如下字符串:

old_string = "I love the number 3 so much"

我想找出整数(在上面的例子中,只有一个数字,3),并用一个大于 1 的值替换它们,即,期望的结果应该是

new_string = "I love the number 4 so much"

在 Python 中,我可以使用:

r = re.compile(r'([0-9])+')
new_string = r.sub(r'\19', s)

在匹配的整数末尾附加一个 9。但是,我想在 \1 上应用一些更通用的东西。

如果我定义一个函数:

def f(i):
    return i + 1

我如何在 \1 上应用 f(),以便我可以用类似 的内容替换 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'
>>>

来自docs :

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

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

关于python - 如何在反向引用上应用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133001/

相关文章:

javascript - 正则表达式替换两个标签之间(外部)的文本

python - 根据主列表对类实例列表进行排序

python - 如何在 Python 中添加包含字典值的列

python - 在共享主机上访问 Django Runserver

objective-c - 如何访问 C 函数中的 N 个参数并将相同的 N 传递给下一个?

C++ 类函数别名

Javascript 函数调用 Socket.io 和 Phaser

python - Bottle pandas 返回 xls 文件

java - 使用java通过使用Microsoft Access数据库中的部分行来搜索数据

regex - Emacs 组织模式链接格式化