【问题标题】:How to determine if variable contains a specified string using RegEx如何使用 RegEx 确定变量是否包含指定的字符串
【发布时间】:2018-10-18 12:44:16
【问题描述】:

我如何编写一个条件,将 Recipient.AdressEntry 例如与使用 RegEx 的以下字符串“I351”进行比较?

这是我的 If 条件,它有效,但被硬编码到每个已知的电子邮件地址。

For Each recip In recips
    If recip.AddressEntry = "Dov John, I351" Then
        objMsg.To = "example@mail.domain"
        objMsg.CC = recip.Address
        objMsg.Subject = Msg.Subject
        objMsg.Body = Msg.Body
        objMsg.Send
    End If
Next

我需要此条件的原因是电子邮件可能包含我团队的几位同事之一和另一个团队的一位或多位同事。我同事的 AdressEntry 以 I351 结尾,所以我会检查这封电子邮件是否包含我的一位队友。

For Each recip In recips
    If (recip.AddressEntry = "Dov John, I351" _
          Or recip.AddressEntry = "Vod Nohj, I351") Then
        objMsg.To = "example@mail.domain"
        objMsg.CC = recip.Address
        objMsg.Subject = Msg.Subject
        objMsg.Body = Msg.Body
        objMsg.Send
    End If
Next

【问题讨论】:

  • 输入的规则是什么? 究竟是什么条件?以I351 结尾的字符串?如果是这样,你甚至不需要正则表达式,你可以简单地使用If recip.AddressEntry Like "*I351",如果不是,请解释输入字符串的规则(又名recip.AddressEntry)。
  • 它是一个对象 Outlook.MeetingItem.Recipient.AdressEntry。我会试试你的建议"*I351"
  • 这不是我的意思。我的意思是输入字符串的格式是什么,您要使用的条件是什么?例如,您是否只想检查字符串是否以“I351”结尾?你想检查它是否匹配两个单词,后跟一个逗号,然后是“I351?或者你到底想检查什么?
  • 我会更新我的问题
  • recip.AddressEntry 返回一个 AddressEntry 对象,而不是字符串。你是说 recip.AddressEntry.Name 吗?

标签: regex vba outlook


【解决方案1】:

您仍然没有准确地说明您要用于匹配的条件是什么,所以我会尽力而为:

  • 如果您只是想检查字符串是否以“I351”结尾,则不需要正则表达式,您可以使用如下内容:

    If recip.AddressEntry Like "*I351" Then
        ' ...
    End If
    
  • 如果您想检查字符串是否遵循这种格式"LastName FirstName, I351",您可以使用正则表达式来实现,方法如下:

    Dim regEx As New RegExp
    regEx.Pattern = "^\w+\s\w+,\sI351$"
    If regEx.Test(recip.AddressEntry) Then
        ' ...
    End If
    

    正则表达式模式的解释:

    ' ^      Asserts position at the start of the string.
    ' \w     Matches any word character.
    ' +      Matches between one and unlimited times.
    ' \s     Matches a whitespace character.
    ' \w+    Same as above.
    ' ,      Matches the character `,` literally.
    ' \s     Matches a whitespace character.
    ' I351   Matches the string `I351` literally.
    ' $      Asserts position at the end of the string.
    

    Try it online.

希望对您有所帮助。

【讨论】:

  • 什么是“测试”,类似于检查是否相等?
  • 没错,它会检查模式后面的字符串中是否有匹配项。
  • RegExp 效果很好,谢谢!!
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 2019-06-11
相关资源
最近更新 更多