【问题标题】:Getting Multiple Repeat Error when using re.search使用 re.search 时出现多次重复错误
【发布时间】:2020-08-20 21:49:04
【问题描述】:

我有一堆 .txt 文件中的电子邮件。我想从电子邮件正文中替换主题。只是主题的上下文。

例如:主题:Re:你在做什么? ,我期待这个主题:Re:。

我已经遍历了所有的 .txt 文件,并将每封电子邮件的主题存储在这样的列表中。

subject list = ['DID HEREALLY RISE???','Q:永远改变图标???','原罪教义'等.....]

为了从文本文件中删除主题,我编写了以下代码: 请注意这只是代码的一部分: subject_line = 实际的subject 来自subject list 上面我提到过:DID HE REALLY RISE???Q: Change icons forever???

subject = 这是来自文本文件的实际内容。我想在文本文件的每一行中搜索subject_line 并用空格替换''

    for subject in file_opened:
      if not bool(re.search(subject_line,subject)):
        file_copy.write(subject)

      if bool(re.search(subject_line,subject)):
        subject = re.sub(subject_line,'',subject)
        file_copy.write(subject)

但我得到了这个错误error: multiple repeat at position 20。 我是正则表达式的新手。我确定我缺少一些模式量词或其他东西。

请帮我解决这个问题。谢谢

【问题讨论】:

    标签: python regex email


    【解决方案1】:

    尝试转义主题行:

    for subject in file_opened:
      if not bool(re.search(re.escape(subject_line), subject)):
        file_copy.write(subject)
    
      if bool(re.search(subject_line, subject)):
        subject = re.sub(re.escape(subject_line), '', subject)
        file_copy.write(subject)
    

    将以下文本用作直接正则表达式模式存在问题:

    DID HE REALLY RISE???
    

    问题在于? 是一个正则表达式元字符,并且具有特殊含义。如果你想搜索这个文字,你应该使用:

    DID HE REALLY RISE\?\?\?
    

    re.escape() 函数会为您处理此正则表达式转义。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多