我在使用 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"