Search code examples
pythonregexpython-re

How to replace different patterns with the same replacement?


I am trying to replace multiple items using regex but am not getting the expected Output. In the below code I need to replace the phone number and the word 'hi' with "X"

txt = "Hi, my phone number is 089992654231. I am 24 years old."

def processString3(txt):
    txt = re.sub('[0-9],Hi]', 'X', txt)
    print(txt)

processString3(txt)

Expected Output - XX, my phone number is XXXXXXXXXX. I am 24 years old.


Solution

  • You might find the following acceptable:

    txt = "Hi, my phone number is 089992654231. I am 24 years old."
    
    def processString3(txt):
        txt = re.sub('[0-9]{5,}|Hi', lambda m: re.sub(r'.', 'X', m.group()), txt)
        print(txt)
    
    processString3(txt)
    # XX, my phone number is XXXXXXXXXXXX. I am 24 years old.
    

    The above logic defines a target phone number as any 5 digits or more in a row. This would exclude ages, which should never be more than 3 digits.