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

前端 未结 4 2093
暗喜
暗喜 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:01

    You can pass a lambda function which uses the Match object as a parameter as the replacement function:

    import re
    re.sub(r'\baword\b', 
           lambda m: m.group(0)[0].lower() == m.group(0)[0] and 'bword' or 'Bword',
           'Aword aword', 
           flags=re.I)
    # returns: 'Bword bword'
    

提交回复
热议问题