如何在反向引用中应用函数? [英] How to apply a function on a backreference?

查看:194
本文介绍了如何在反向引用中应用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  old_string =我非常喜欢数字3

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

  new_string =我非常喜欢数字4

在Python中,我可以使用:

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

附加一个 9 在匹配的整数数字的末尾。不过,我想在 \ 1 上应用更一般的东西。如果我定义一个函数:

  def f(i)
$ b


返回i + 1

如何申请 f( )在 \ 1 上,这样我就可以用 old_string 中的匹配字符串替换类似于 f(\ 1)

解决方案

有一个替换字符串, re.sub 允许你使用一个函数来替换:

 >>> import re 
>>> old_string =我非常喜欢数字3
>>> def f(match):
... return str(int(match.group(1))+ 1)
...
>>> re.sub('([0-9])+',f,old_string)
'我非常喜欢数字4'
>>>




re。re.html#re.subrel =noreferrer> docs sub(pattern,repl,string,count = 0,flags = 0)



如果 repl 是一个函数,它被称为每个非重叠的
出现的 pattern 。该函数接受一个匹配对象
参数,并返回替换字符串。



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)?

解决方案

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.

这篇关于如何在反向引用中应用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆