如果字符串在whitelist
而不是blacklist
中,我想获取匹配项。我的问题是这两张单子之间可能有重叠。
到目前为止,我的白名单工作使用
whitelist = ["but"]
blacklist = ["but now"]
# Correct, I get 'this is a test but\n not really'
re.sub(r"\b(" + r"|".join(whitelist) + r")\b", "\\1\n", "this is a test but not really")
有没有一种有效的方法来使用whitelist
和blacklist
构建正则表达式,以便得到这种结果
efficient_regex = f(whitelist, blacklist)
re.sub(efficient_regex, "\\1\n", "this is a test but now it does not matter")
# And not 'this is a test but\n now it does not matter'
我正想弄清楚regexp的用法,但到目前为止还不能用
我最终找到了一个使用单个正则表达式的解决方案,它使用
negative lookahead assertion
和negative lookbehind assertion
然后只能使用一个正则表达式来进行替换
应该可以从
whitelist
和blacklist
生成regex,但我还没有尝试你可以试试这样的方法:
相关问题 更多 >
编程相关推荐