2016-09-18 15 views
1

在Python字,我试图做正则表达式 - 替换有加或支架

text = re.sub(r'\b%s\b' % word, "replace_text", text) 

一些文字来代替一个字。使用re而不是仅仅使用text.replace替换,只有整个单词匹配使用\b。问题出现时,字中有像+, (, [ etc这样的字符。例如+91xxxxxxxx

正则表达式会将此+视为一个或多个通配符并打破错误。 sre_constants.error: nothing to repeat(也是如此。

找到一个解决方案后,搜索了一下。有没有办法?

回答

2

只需使用re.escape(string)

word = re.escape(word) 
text = re.sub(r'\b{}\b'.format(word), "replace_text", text) 

它取代了所有重要的人物有着特殊含义的正则表达式模式与他们逃跑的形式(例如的替代\++)。


仅有旁注:用百分比格式化(%)字符已被弃用,通过串的.format()方法代替。