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

7 投票
3 回答
9211 浏览
提问于 2025-04-16 10:40

我有一个简单的函数,用来从一些文本中去掉一个“单词”:

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 个回答

-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)   
0

除非你必须使用正则表达式,不然你可以用字符串的 replace 方法来代替吗?

text = text.replace(word, '')

这样可以帮你解决标点符号的问题。

24

你可以用 re.escape(word) 来处理这个词,让它变得安全。

撰写回答