使用 re.sub() 时无效的组引用 [英] invalid group reference when using re.sub()
问题描述
我在使用 re.sub 时遇到了麻烦.我从其他答案中了解到这是因为我引用了一个我没有的捕获组.
I'm having troubles with re.sub. I understand from other answers that this is due to the fact I'm referencing to a capturing group that I don't have.
我的问题是:如何调整我的代码以拥有一个有效的组?
My question is: how do I adjust my code to have a valid group?
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 a world today b is nice c day"
I want to have this : "hello <b>a world today b is sunny c</b> day"
推荐答案
如果模式中没有捕获组,则不能使用 \1
替换反向引用.将捕获组添加到模式:
You cannot use \1
replacement backreference if there are no capturing groups in the pattern. Add the capturing group to the pattern:
pattern = r'\b(' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r')\b' # or
^ ^
pattern = r'\b({})\b'.format(r' (?:\w+ )?(?:\w+ )?'.join(markers))
或者,只需使用 \g<0>
插入整个匹配项而不是捕获组值(然后,无需修改您的正则表达式):
Or, just use the \g<0>
to insert the whole match rather than a capturing group value (then, there is no need amending your regex):
text = re.sub(pattern, r'<b>\g<0></b>', s)
请参阅 Python 演示.
这篇关于使用 re.sub() 时无效的组引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!