首页 > 解决方案 > 在python中用正则表达式将括号括起来

问题描述

我想在可以在句子中包含字母或点的表达式周围添加括号。

我试过这个功能:

def add_brackets(sentence, word):
    s = r'(\b' + word + r'\b)' 
    c  = re.compile(s, re.I)
    return(c.sub(r'[\1]', sentence))

sentence = 'Le pressostat h.p. est installé'
word = 'est installé'

输出很好:

'Le pressostat h.p. [est installé]'

但是:

sentence = 'Le pressostat h.p. est installé'
word = 'pressostat h.p.'

输出没有括号:

'Le pressostat h.p. est installé'

但随着

sentence = 'Le pressostat h.p. est installé'
word = 'pressostat h.p' #no final dot

输出带有括号:

'Le [pressostat h.p]. est installé'

问题可能是最后的'。因为没有它,功能就可以工作。如何在正则表达式中包含点?

标签: pythonregex

解决方案


推荐阅读