Home > Blockchain >  Python regex replace list of pattern
Python regex replace list of pattern

Time:04-14

I have a list of patterns:

patterns = ["how", "do you do", "are you doing", "goes it"]

Any occurrences of list's items in string should be replaced to "how are you".

For example:

String "how do you do?" should be replaced to "how are you?"

What I use:

s = input()  
for pattern in patterns:
       s = re.sub(rf"(\b{pattern}\b)", "how are you", s)

The problem is that I receive "how are you how are you".

The easiest solution is to change list of patterns to:

patterns = ["how do you do", "how are you doing", "how goes it"]

But I need to keep "how" in list and keep it separately from other items.

CodePudding user response:

The problem is related with the s inside and outside the re.sub, this overwrite the input() Use another varialbe, like m

s = input()  
for pattern in patterns:
    m = re.sub(rf"(\b{pattern}\b)", "how are you", s)

CodePudding user response:

Would you please try the following:

import re

patterns = ["how", "do you do", "are you doing", "goes it"]
first = patterns.pop(0)                 # pop the 1st element
pattern = rf"\b{first}\s (?:"   "|".join(patterns)   r")\b"
# pattern equals to r"\bhow\s (?:do you do|are you doing|goes it)\b"
s = input()
s = re.sub(pattern, "how are you", s)
print(s)

If you prefer to using a loop, here is an alternative:

import re

patterns = ["how", "do you do", "are you doing", "goes it"]
first = patterns.pop(0)                 # pop the 1st element
s = input()
for pattern in patterns:
    s = re.sub(rf"\b{first}\s {pattern}\b", "how are you", s)
print(s)
  • Related