Python:动态构建正则表达式的最佳实践

时间:2011-01-26 16:35:34

标签: python 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)    

问题当然是,如果单词包含诸如“(”或“)”之类的字符,那么事情就会中断,并且在正则表达式的中间粘贴一个随机单词通常似乎不安全。

处理此类案件的最佳做法是什么?是否有一个方便,安全的功能,我可以调用以逃避“单词”,这样可以安全使用?

3 个答案:

答案 0 :(得分:21)

您可以使用re.escape(word)来逃避这个词。

答案 1 :(得分:0)

除非你被迫使用正则表达式,否则你不能使用replace方法来代替字符串吗?

text = text.replace(word, '')

这可以让你摆脱ponctuation问题。

答案 2 :(得分:-1)

编写一个清洁剂功能并首先传递一个字。

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)   
相关问题