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'\baword\b', 'bword', mystring)
What I'd really like is some sort of conditional substitution notation like:
re.sub(r'\b([Aa])word\b', '(?1=A:B,a:b)word')
I only care about the capitalization of the first character. None of the others.
To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.
When using the . replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify.
We can use regex to replace multiple patterns at one time using regex.
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.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With