Python re.sub 问题

21 投票
3 回答
17574 浏览
提问于 2025-04-15 18:12

大家好,

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

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 个回答

2

在编程中,我们常常会遇到一些问题,尤其是在使用某些工具或库的时候。有时候,错误信息可能会让人感到困惑,特别是对于刚开始学习编程的人来说。

比如,当你在运行代码时,可能会看到一些提示,告诉你哪里出了问题。这些提示通常会包含一些技术术语,可能让你觉得难以理解。

解决这些问题的一个好方法是查阅相关的文档或在网上搜索类似的问题。很多时候,其他人也遇到过相同的情况,他们的解决方案可能会对你有帮助。

另外,尝试逐步调试你的代码也是一个不错的选择。你可以逐行检查代码,看看每一步的输出是什么,这样可以帮助你找到问题所在。

总之,遇到问题时不要气馁,保持耐心,慢慢来,很多问题都是可以解决的。

>>> 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:]]'
8

听起来有点过于复杂了。为什么不直接做一些简单的事情,比如

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

呢?

36

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

另外,注意正则表达式中的额外问号。这是为了让匹配变得不那么贪婪。

我明白这只是示例代码,用来说明一个概念,但对于你给出的例子,简单的字符串格式化会更好。

撰写回答