代码之家  ›  专栏  ›  技术社区  ›  netricate

python re.sub问题

  •  15
  • netricate  · 技术社区  · 16 年前

    问候大家,

    我不确定这是否可行,但我想在正则表达式替换中使用匹配的组来调用变量。

    a = 'foo'
    b = 'bar'
    
    text = 'find a replacement for me [[:a:]] and [[:b:]]'
    
    desired_output = 'find a replacement for me foo and bar'
    
    re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid
    re.sub('\[\[:(.+):\]\]','\1',text) #replaces the value with 'a' or 'b', not var value
    

    思想?

    3 回复  |  直到 16 年前
        1
  •  26
  •   Christian Oudard    16 年前

    使用re.sub时,可以指定回调,它可以访问组: http://docs.python.org/library/re.html#text-munging

    a = 'foo'
    b = 'bar'
    
    text = 'find a replacement for me [[:a:]] and [[:b:]]'
    
    desired_output = 'find a replacement for me foo and bar'
    
    def repl(m):
        contents = m.group(1)
        if contents == 'a':
            return a
        if contents == 'b':
            return b
    
    print re.sub('\[\[:(.+?):\]\]', repl, text)
    

    还要注意额外的吗?在正则表达式中。你想要非贪婪的匹配。

    我理解这只是用来说明概念的示例代码,但是对于您给出的示例,简单的字符串格式更好。

        2
  •  8
  •   Noufal Ibrahim    16 年前

    听起来像是杀戮过度。为什么不做点像

    text = "find a replacement for me %(a)s and %(b)s"%dict(a='foo', b='bar')
    

    ?

        3
  •  2
  •   ghostdog74    16 年前
    >>> d={}                                                
    >>> d['a'] = 'foo'                                      
    >>> d['b'] = 'bar' 
    >>> text = 'find a replacement for me [[:a:]] and [[:b:]]'
    >>> t=text.split(":]]")
    >>> for n,item in enumerate(t):
    ...   if "[[:" in item:
    ...      t[n]=item[: item.rindex("[[:") +3 ] + d[ item.split("[[:")[-1]]
    ...
    >>> print ':]]'.join( t )
    'find a replacement for me [[:foo:]] and [[:bar:]]'