Lyesgigs
Lyesgigs

Reputation: 129

Python , regular expressions, replace text containing a word

I wanna replace all text if it contains a given word ( example : 'mama') . i used the following code:

import re 
text1 = 'I love mama so much'
result = re.sub(r"\bmama\b",'Nice', text1)
print (result)

The result of this is : 'I love Nice so much', however i want it to be only 'Nice'.

How can i do that ? Thanks.

Upvotes: 0

Views: 1594

Answers (6)

Vimal Raj
Vimal Raj

Reputation: 544

It is base case so

you can use this code as follows

import re 
text1 = 'I love mama so much'
result = re.sub(r"m..a",'Nice', text1)
print(result)

It can help you on base case..!

Upvotes: 0

Magnetron
Magnetron

Reputation: 377

You can wrap the the regex string in wildcards.

result = re.sub(r".*\bmama\b.*",'Nice', text1)

. stands for any character and * stands for 0+ amount of the character to the left of it.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You need to use

import re 
text1 = 'I love mama so much'
result = 'Nice' if re.search(r"\bmama\b", text1) else text1
print(result)

See the Python demo online

The 'Nice' if re.search(r"\bmama\b", text1) else text1 line means that if there is a regex match of mama as a whole word in text1, the result should be equal to Nice, else, it should be equal to text1.

Please mind that re.search searches for a match anywhere inside a string while re.match will only look for matches at the start of a string.

Upvotes: 0

ARNAV RAMKRISHNAN
ARNAV RAMKRISHNAN

Reputation: 164

If you want the result to be 'Nice',

result = 'Nice'

If there's extra condition that 'Nice' must be in your expression, add an if statement

if 'mama' in text1:
    result = 'Nice';

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12157

That's what re.sub does. If you want to replace the whole string (with regex), do

text1 = 'I love mama so much'
if re.search(r' mama ', text1):
     text1 = 'Nice'

Upvotes: 0

Dan
Dan

Reputation: 45752

If you're not specifically looking for a regex solution you can do it like this (I'm assuming if it doesn't contain 'mama' you want to return the original phrase?):

result = 'Nice' if 'mama' in text1 else text1

Upvotes: 1

Related Questions