Replacing repeated captures

后端 未结 4 1901
悲哀的现实
悲哀的现实 2021-02-18 13:11

This is sort of a follow-up to Python regex - Replace single quotes and brackets thread.

The task:

Sample input strings:

RSQ(nam         


        
4条回答
  •  渐次进展
    2021-02-18 13:19

    You could do this. Though I don't think it's very readable. And doing it this way could get unruly if you start adding more patterns to replace. It takes advantage of the fact that the replacement string can also be a function.

    s = "RSQ(name['BAKD DK'], name['A DKJ'])"
    re.sub(r"^(\w+)|name\['(.*?)'\]", lambda m: 'XYZ' if m.group(1) else m.group(2), s)
    

提交回复
热议问题