相关疑难解决方法(0)

使用 re.sub() 时无效的组引用

我在使用 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
Run Code Online (Sandbox Code Playgroud)

我想要这个: "hello <b>a world today b is sunny c</b> day"

python regex replace

5
推荐指数
1
解决办法
4708
查看次数

标签 统计

python ×1

regex ×1

replace ×1