【问题标题】:Regex - replace word having plus or brackets [duplicate]正则表达式 - 替换带有加号或括号的单词[重复]
【发布时间】:2017-01-26 03:37:24
【问题描述】:

在 Python 中,我正在尝试做

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

用一些文本替换一个单词。仅当整个单词与使用\b 匹配时才使用re 而不是仅仅使用text.replace 来替换。当 word 中有 +, (, [ etc 这样的字符时,问题就来了。例如+91xxxxxxxx

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

搜索了一下后可以找到解决此问题的方法。有什么办法吗?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    只需使用re.escape(string):

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

    它将正则表达式模式中具有特殊含义的所有关键字符替换为其转义形式(例如\+ 而不是+)。


    只是一个旁注:使用百分比 (%) 字符进行格式化已被弃用,并被字符串的 .format() 方法所取代。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多