[英]Python: Best practice for dynamically constructing regex
我有一个简单的函数可以从某些文本中删除“单词”:
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)
当然,问题在于如果单词包含诸如“(”或“)”之类的字符,则事情会中断,并且在正则表达式中间插入随机单词通常似乎不安全。
处理此类案件的最佳做法是什么? 是否有一个方便、安全的函数可以调用来转义“单词”,以便安全使用?
您可以使用re.escape(word)
来转义单词。
除非您被迫使用正则表达式,否则您不能使用replace
字符串的方法吗?
text = text.replace(word, '')
这使您可以摆脱标点符号问题。
编写一个 sanitizer 函数并首先通过它传递信息。
def sanitize(word):
def literalize(wd, escapee):
return wd.replace(escapee, "\\%s"%escapee)
return reduce(literalize, "()[]*?{}.+|", word)
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + sanitize(word) + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.