How to write a regular expression to replace a word but save it in Python?

Is it possible?

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

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

What I really liked is a kind of conditional substitution of type substitution:

 re.sub(r'\b([Aa])word\b', '(?1=A:B,a:b)word') 

I only like the capitalization of the first character. None of the others.

+4
source share
3 answers

You can have functions to parse each 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' 
+8
source

OK, here is the solution I came across thanks to suggestions to use the replace function.

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

You can pass a lambda function that uses the Match object as a parameter as a 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' 
+4
source

All Articles