简体   繁体   中英

Python regex replace list of pattern

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM