Python 正则表达式替换模式列表

Python regex replace list of pattern

我有一个模式列表:

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

字符串中出现的任何列表项都应替换为 "how are you"

例如:

字符串 "how do you do?" 应替换为 "how are you?"

我用的是:

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

问题是我收到 “你好吗?”

最简单的解决方案是将模式列表更改为:

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

但我需要将“如何”保留在列表中,并将其与其他项目分开。

问题与re.sub内外的s有关,这个覆盖了input() 使用另一个变量,例如 m

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

请您尝试以下操作:

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)

如果您更喜欢使用循环,这里有一个替代方案:

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)