【问题标题】:Negating ")" inside a regex search pattern [duplicate]在正则表达式搜索模式中否定“)”[重复]
【发布时间】:2018-05-18 08:05:18
【问题描述】:

我正在尝试在 python 中使用正则表达式来替换字符串。我想将字符串中的“SERVERS)”替换为“SERV”。

example_String = "This is a great SERVERS)"

re.sub("SERVERS)","SERV", example_String)

我希望它是一个直接的交换,但是当我更多地阅读错误时,看起来我需要将正则表达式模式设置为将“)”读取为常规字符而不是特殊的正则表达式字符。

我对 regex 不是很熟悉,希望能得到帮助!

编辑:我正在从数据库中导入数据(这是用户输入),问题中提到了很多类似的问题。 re.escape() 完全符合要求,谢谢!

【问题讨论】:

    标签: python regex


    【解决方案1】:

    你可以去

    import re
    
    example_String = "This is a great SERVERS)"
    new_string = re.sub(r"SERVERS\)","SERV", example_String)
    print(new_string)
    

    产量

    This is a great SERV
    


    老实说,不需要正则表达式,真的:
    example_String = "This is a great SERVERS)"
    new_string = example_String.replace('SERVERS)', 'SERV')
    print(new_string)
    

    在后者中,你甚至不需要逃避任何东西,它会更快。

    【讨论】:

    • 如果是用户输入的SERVERS)也可以使用python的re.escape()方法
    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2023-01-30
    • 2021-02-09
    • 2014-12-28
    相关资源
    最近更新 更多