正则表达式,但用于在匹配中写入

2024-05-23 13:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用正则表达式时,我们通常(如果不总是)使用它们来提取某种信息。我需要的是用其他值替换匹配值。。。在

现在我在做这个。。。在

def getExpandedText(pattern, text, replaceValue):
    """
        One liner... really ugly but it's only used in here.
    """

    return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
            text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]

所以如果我做某事

^{pr2}$

它用“ooo”改变了(…)。在

你们知道用python正则表达式我们能否做到这一点吗?在

谢谢大家!!在


Tags: textre信息defitfindonebut
3条回答

当然。请参阅编译正则表达式的“sub”和“subn”方法,或re.sub公司'和're.subn公司'功能。您可以让它用给定的字符串参数替换匹配项,也可以传递将被调用以提供替换项的可调用项(如函数)。见https://docs.python.org/library/re.html

您要使用re.sub

>>> import re
>>> re.sub(r'aaa...bbb', 'aaaooobbb', "hola aaaiiibbb como estas?")
'hola aaaooobbb como estas?'

要重用模式中的变量部分,请在替换字符串中使用\g<n>来访问第n个()组:

^{pr2}$
sub (replacement, string[, count = 0])

sub返回通过替换替换替换替换RE-in字符串中最左边不重叠的实例而获得的字符串。如果找不到模式,字符串将原封不动地返回。在

^{pr2}$

相关问题 更多 >