【问题标题】:How to replace special regex chars in Python? [duplicate]如何在 Python 中替换特殊的正则表达式字符? [复制]
【发布时间】:2016-11-20 05:36:13
【问题描述】:

我需要匹配以下模式:

text1.cps.text2
text1.text2.cps.text3
cps.text1

其中 text1, text2 是一些随机词。 cps 是几个可能的词之一。所以我写了以下正则表达式:

pattern = "(\w+\.)*?({0})(\w+\.)*"

然后我遍历可能的单词列表:

for word in ['cps.','cps.tbl.']:
   p = pattern.format(word)

所以问题是可能单词中的项目可能包含特殊的正则表达式字符。所以我正在寻找将每个特殊字符替换为类似内容的函数:

cps\. and cps\.tbl\.

【问题讨论】:

  • 你试过原始字符串吗?

标签: python regex escaping


【解决方案1】:

re 模块定义了一个 escape 函数,它就是这样做的。比如:

for word in words:
    pattern = re.escape(word)
    ...

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多