【问题标题】:invalid group reference when using re.sub()使用 re.sub() 时组引用无效
【发布时间】:2018-07-20 02:45:01
【问题描述】:

我在使用 re.sub 时遇到了问题。我从其他答案中了解到,这是因为我引用了一个我没有的捕获组。

我的问题是:如何调整我的代码以获得有效的组?

s = "hello a world today b is sunny c day"
markers = "a b c".split()
pattern = r'\b' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r'\b'
text = re.sub(pattern, r'<b>\1</b>', s)   # this gives error

我想要这个:"hello &lt;b&gt;a world today b is sunny c&lt;/b&gt; day"

【问题讨论】:

    标签: python regex replace


    【解决方案1】:

    如果模式中没有捕获组,则不能使用 \1 替换反向引用。将捕获组添加到模式中:

    pattern = r'\b(' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r')\b' # or
                  ^                                            ^
    pattern = r'\b({})\b'.format(r' (?:\w+ )?(?:\w+ )?'.join(markers))
    

    或者,只需使用 \g&lt;0&gt; 插入整个匹配项而不是捕获组值(这样,就无需修改您的正则表达式):

    text = re.sub(pattern, r'<b>\g<0></b>', s) 
    

    请参阅Python demo

    【讨论】:

      【解决方案2】:

      您的正则表达式中没有任何组。

      (?:...) 是非捕获组,我猜你想要

      pattern = r'\b(' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r')\b'
      

      【讨论】:

        【解决方案3】:

        这段代码可以得到你想要的结果。我已经测试过了。

        import re
        s = "hello a world today b is sunny c day"
        pat = r'(a.*c)'
        result = re.sub(pat,r'<b>\1</b>',s)
        

        【讨论】:

          猜你喜欢
          • 2017-12-25
          • 2016-05-23
          • 1970-01-01
          • 1970-01-01
          • 2023-01-14
          • 2012-11-18
          • 2014-01-12
          • 1970-01-01
          相关资源
          最近更新 更多