Python 使用re.sub()时组引用无效
我和re.sub有麻烦。我从其他答案中了解到,这是因为我引用了一个我没有的捕获组 我的问题是:如何调整代码以获得有效的组Python 使用re.sub()时组引用无效,python,regex,replace,Python,Regex,Replace,我和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) # th
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
s=“你好a今天的世界b是阳光明媚的c日”
markers=“a b c”.split()
pattern=r'\b'+'(?:\w+)(?:\w+)。连接(标记)+r'\b'
text=re.sub(模式,r'\1',s)#这会产生错误
我想要这样:
“你好,今天的世界b是晴朗的c天”
您的正则表达式中没有任何组
(?:…)
是一个非捕获组,我想您需要
pattern = r'\b(' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r')\b'
如果模式中没有捕获组,则不能使用
\1
替换反向引用。将捕获组添加到模式:
pattern = r'\b(' + ' (?:\w+ )?(?:\w+ )?'.join(markers) + r')\b' # or
^ ^
pattern = r'\b({})\b'.format(r' (?:\w+ )?(?:\w+ )?'.join(markers))
或者,只需使用\g
插入整个匹配项,而不是捕获组值(这样,就不需要修改正则表达式):
text=re.sub(模式,r'\g',s)
请参阅。此代码可以得到您想要的结果。我已经测试过了
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)
重新导入
s=“你好,a今天的世界b是晴朗的c天”
pat=r'(a.*c)'
结果=re.sub(pat,r'\1',s)
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)