【问题标题】:Python re.sub questionPython re.sub 问题
【发布时间】:2010-01-19 16:20:39
【问题描述】:

大家好,

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

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

想法?

【问题讨论】:

  • 哈!并不真地。熟悉 py、perl 和 php - 无一精通。谢谢你的帮助:)

标签: python regex


【解决方案1】:

您可以在使用 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)

还注意到额外的吗?在正则表达式中。你想在这里进行非贪婪匹配。

我知道这只是说明一个概念的示例代码,但是对于您提供的示例,简单的字符串格式更好。

【讨论】:

  • 感谢代码!这实际上更接近我的想法。
  • 我回答了你的问题,但我认为你问错了问题。在适当的时候,请优先使用字符串格式而不是正则表达式。 Noufal Ibrahim 回答了你应该问的问题。
  • 不要忘记返回语句中的引号。 :)
【解决方案2】:

听起来有点矫枉过正。为什么不做类似的事情

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

?

【讨论】:

  • 文本存储在数据库中。我想我可以用 %() 值替换所有 [[::]] 值,这应该可以。我会试一试。谢谢!
  • 这个方法要看你是否知道[[:a:]]和[[:b:]]的位置。
  • 有很多问题,但 OP 试图做的在概念上与字符串格式化相同。
【解决方案3】:
>>> 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:]]'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多