如何替换电子邮件中两个关键词之间的句子



我之前在regex的这个链接上问了一个问题如何在转发电子邮件之前删除2个单词之间的某些句子?

我回去尝试了一下这个建议,并提出了一些意见。下面是我尝试的脚本:

  1. 更改电子邮件主题
  2. 在电子邮件正文中插入新行
  3. 查找并替换电子邮件正文中"影响"one_answers"纠正措施"之间的句子
  4. 转发电子邮件
Set FwdMsg = item.Forward
With FwdMsg
Dim regEx As New RegExp
   With regEx
     .Global = False
     .multiline = True
     .ignorecase = False
     .pattern = strPattern
    End With
    Dim newbody As String
    Dim source As String
    source = FwdMsg.HTMLBody
    Dim replacestr As String
    replacestr = "$1nnplease call me with this numbernn$2"
    strPattern = "^(Impact:)s*(?:(?!^(?:Impact:|Correction[^Sn]+Action))[sS])*^(Correction[^Sn]+Action)"
    newbody = regEx.replace(source, replacestr)
    FwdMsg.HTMLBody = newbody
    NewLine = "Dear users,Please note that data is also affected by the incident below and will be corrected. Please email  for more information."
    FwdMsg.HTMLBody = NewLine & FwdMsg.HTMLBody 
    FwdMsg.Recipients.Add "xx.com.sg"
    FwdMsg.Subject = "Incident" & Format$(Now, " dd-mm-yyyy hh.mmam/pm")

不知怎么的,当我在Outlook上写剧本时,我注意到了一些事情。

  1. 代码无法定位单词"影响"one_answers"纠正行动"之间的句子,因此这些句子不会被删除
  2. replacestr行会显示在电子邮件中,但不会替换单词"影响"one_answers"纠正行动"之间的句子

有什么想法吗?

在我看来,您在使用strPattern之前没有初始化它:

With regEx
 .Global = False
 .multiline = True
 .ignorecase = False
 .pattern = strPattern ' empty string ""
End With

在这一点上,没有任何东西被分配给strPattern,所以它只包含一个空字符串""。因此,您的正则表达式实际上是在查找第一个出现的"",我想它可以在您的电子邮件开头找到。这显然不是你想要的。

要解决此问题,请向上移动为strPattern赋值的行,使其出现在您使用该变量的位置之前,例如

strPattern = "^(Impact:)s*(?:(?!^(?:Impact:|Correction[^Sn]+Action))[sS])*^(Correction[^Sn]+Action)"
With regEx
 .Global = False
 .multiline = True
 .ignorecase = False
 .pattern = strPattern ' now it contains what you're looking for.
End With

或者,完全去掉那个无用的临时变量!我看不出你在其他地方使用它,所以为什么不直接内联呢?

With regEx
 .Global = False
 .multiline = True
 .ignorecase = False
 .pattern = "^(Impact:)s*(?:(?!^(?:Impact:|Correction[^Sn]+Action))[sS])*^(Correction[^Sn]+Action)"
End With

怎么样

(Impact:n)[sw]*(nCorrectives*Action)

将脚本更改为

replacestr = "$1nnplease call me with this numbernn$2"
strPattern = "(Impact:n)[sw]*(nCorrectives*Action)"

将产生输出

Impact:
please call me with this number
Corrective Actio

请参阅regex上的示例http://regex101.com/r/gU3aS1/2

最新更新