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

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'

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.')

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'

Tags:

Python

Regex