【问题标题】:Python: Regex Search Special Characters giving errors while searching multiple charactersPython:正则表达式搜索特殊字符在搜索多个字符时出错
【发布时间】:2017-11-09 23:15:42
【问题描述】:

我正在使用包的 findall() 函数进行简单的正则表达式字符串搜索。 在使用负面场景进行单元测试时,我发现一些特殊字符正在返回错误代码,这些错误代码在 # 符号之后的下面的 cmets 中给出。 我的问题是为什么这些字符返回错误代码以及如何用带有转义序列的搜索字符串替换它们? 请告诉我替换转义序列的代码:

import re
search="database"
search="c++" # error: multiple repeat
search="c\+\+" #working
search="c+"  #working
search="c#" #working
search="j!!" #working
search="x$$" #working
search="++j" #error: nothing to repeat
search="~~c" #working
search="c@@" #working
search="j##" #working
search="c%%"  #working
search="j&&"  #working
search="j**" #error: multiple repeat
search="j*"  #* is wild card
search="c(github)" #working
search="c--" #working
search="c==" #working
document="i did c++ programming. I am a c++ programming enthusiast. I love 
working on c++ algirithms. I have experience in 3.5 years of c++ programming 
skills "
n=len(re.findall(search,document))
print("Keyword Frequency: ",search ," Count:  ",n)

代码 print() 的最后一条语句的输出针对每个搜索词给出,以便于理解。 我需要的解决方案必须具备以下能力:

  1. 识别特殊字符序列。 (例如它可以是:++ 或 +++ 或 +++++ 或 "++j" 或 "j**" 等

  2. 识别特殊字符序列后,解决方案代码应将特殊字符替换为“++”或“+++”或“+++++”或“++j”或“j**”

  3. 创建新的搜索字符串

提前感谢您的解决方案。

【问题讨论】:

    标签: regex python-3.x search


    【解决方案1】:

    正则表达式模块附带了一个功能:re.escape()。所以:

    import re
    
    search = "c++"
    # ...
    document = """i did c++ programming. I am a c++ programming enthusiast. I love 
    working on c++ algirithms. I have experience in 3.5 years of c++ programming 
    skills """
    n = len(re.findall(re.escape(search), document))
    print("Keyword Frequency: ", search, " Count:  ", n)
    

    应该没问题...现在,您为什么要使用正则表达式而不是 str.count() 来完成如此简单的任务,这是您需要自己回答的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多