How do I write a regex to replace a word but keep its case in Python?

前端 未结 4 2072
暗喜
暗喜 2021-01-01 00:48

Is this even possible?

Basically, I want to turn these two calls to sub into a single call:

re.sub(r\'\\bAword\\b\', \'Bword\', mystring)
re.sub(r\'\         


        
4条回答
  •  醉梦人生
    2021-01-01 01:03

    OK, here's the solution I came up with, thanks to the suggestions to use a replace function.

    re.sub(r'\b[Aa]word\b', lambda x: ('B' if x.group()[0].isupper() else 'b') + 'word', 'Aword  aword.')
    

提交回复
热议问题