处理正则表达式中的不平衡括号

时间:2015-07-10 05:58:55

标签: python regex

我对正则表达式不太满意。我使用以下正则表达式来替换字符串中的特定单词,只有当单词没有出现在引号内时。

re.sub(r'("[^"]*")|%s' %word, lambda m: m.group(1) if m.group(1) else "", query)

效果很好。除了query = MBA in Human Resource Management (Jaipur National University)时,我收到以下错误。

error: unbalanced parenthesis

此实例中word的值为(Jaipur

如何修复正则表达式以处理不平衡的括号?

1 个答案:

答案 0 :(得分:2)

问题是当word"(Jaipur"时,您的正则表达式为r'("[^"]*")|(Jaipur',但您希望它为r'("[^"]*")|\(Jaipur'。要解决此问题,您可以使用re.escape(word)而不仅仅word

re.sub(r'("[^"]*")|%s' % re.escape(word), lambda m: m.group(1) if m.group(1) else "", query)

(见the documentation for re.escape。)

相关问题