【问题标题】:How to replace sentences between 2 key words in an email?如何替换电子邮件中两个关键词之间的句子?
【发布时间】:2014-12-21 05:37:12
【问题描述】:

我之前在这个链接上问过一个关于正则表达式的问题 How to delete certain sentences between 2 words before forwarding the email?

我回去尝试了这个建议并做了一些观察。 以下是我尝试的脚本:

  1. 更改电子邮件主题
  2. 在电子邮件正文中插入新行
  3. 找到并替换电子邮件正文中“影响”和“纠正措施”之间的句子
  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 = "$1\n\nplease call me with this number\n\n$2"
    strPattern = "^(Impact:)\s*(?:(?!^(?:Impact:|Correction[^\S\n]+Action))[\s\S])*^(Correction[^\S\n]+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. 代码无法找到 Impact 和 Correction Action 之间的句子,因此不会删除这些句子。
  2. replacestr 行会显示在电子邮件中,但不会替换 Impact 和 Correction Action 之间的那些句子。

有什么想法吗?

【问题讨论】:

  • 您能提供必须匹配和不匹配的字符串示例吗?

标签: regex vba email outlook


【解决方案1】:

在我看来你在使用之前没有初始化strPattern

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

此时,尚未将任何内容分配给strPattern,因此它只包含一个空字符串""。所以你的正则表达式实际上是在寻找"" 的第一次出现,我认为它会在你的电子邮件开头找到。这显然不是你想要的。

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

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

或者,完全摆脱那个无用的临时变量!我没有看到您在其他任何地方使用它,所以为什么不只是 inline 它。

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

【讨论】:

  • 非常感谢所有回复的人。我的脚本正在运行。我开始喜欢这个网站。干杯!
【解决方案2】:

怎么样

(Impact:\n)[\s\w]*(\nCorrective\s*Action)

将脚本更改为

replacestr = "$1\n\nplease call me with this number\n\n$2"
strPattern = "(Impact:\n)[\s\w]*(\nCorrective\s*Action)"

将产生输出为

Impact:

please call me with this number

Corrective Actio

查看正则表达式http://regex101.com/r/gU3aS1/2上的示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2022-08-09
    相关资源
    最近更新 更多