How to apply a function on a backreference?

跟風遠走 提交于 2019-12-30 07:06:08

问题


Say I have strings like the following:

old_string = "I love the number 3 so much"

I would like to spot the integer numbers (in the example above, there is only one number, 3), and replace them with a value larger by 1, i.e., the desired result should be

new_string = "I love the number 4 so much"

In Python, I can use:

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

to append a 9 at the end of the integer numbers matched. However, I would like to apply something more general on \1.

If I define a function:

def f(i):
    return i + 1

How do I apply f() on \1, so that I can replace the matched strings in old_string with something like f(\1)?


回答1:


In addition to having a replace string, re.sub allows you to use a function to do the replacements:

>>> 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'
>>>

From the 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.



来源:https://stackoverflow.com/questions/28133001/how-to-apply-a-function-on-a-backreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!