【发布时间】:2019-06-24 19:09:47
【问题描述】:
s = "[abc]abx[abc]b"
s = re.sub("\[([^\]]*)\]a", "ABC", s)
'ABCbx[abc]b'
在字符串 s 中,当它被 [] 括起来时,我想匹配 'abc',然后是 'a'。所以在那个字符串中,第一个 [abc] 将被替换,而第二个不会。
我写了上面的模式,它匹配:
match anything starting with a '[', followed by any number of characters which is not ']', then followed by the character 'a'.
但是,在替换中,我希望字符串如下:
[ABC]abx[abc]b . // NOT ABCbx[abc]b
也就是说,我不希望替换整个匹配的模式,而只替换带有括号 [] 的任何内容。如何实现?
match.group(1) 将返回 [] 中的内容。但是如何在 re.sub 中利用这一点呢?
【问题讨论】: