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

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

    You can have functions to parse every match:

    >>> def f(match):
            return chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:]
    
    >>> re.sub(r'\b[aA]word\b', f, 'aword Aword')
    'bword Bword'
    

提交回复
热议问题