Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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.

like image 296
Conley Owens Avatar asked Jun 30 '12 16:06

Conley Owens


People also ask

How do I replace a word in a string in regex?

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.

How do you replace one word with a string in Python?

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.

Can regex be used with replace in Python?

We can use regex to replace multiple patterns at one time using regex.


2 Answers

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'
like image 130
JBernardo Avatar answered Oct 19 '22 22:10

JBernardo


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.')
like image 41
Conley Owens Avatar answered Oct 20 '22 00:10

Conley Owens