VBA正则表达式

时间:2017-01-20 13:36:13

标签: regex vba

我正在尝试循环浏览电子邮件正文并将电子邮件转发到其他收件箱。我的正则表达式匹配任何4-6个字符数字前后有空格,但问题是日期包含在电子邮件中,所以它也拾取了四个字符数“2017”。什么是正则表达式省略“2017”,并采取所有其他4-6个字符数字。这是我的代码。

Option Explicit
Public Sub Forward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match
    Dim Reg1 As Object
    Dim myForward As Object

    Set Reg1 = New RegExp

    With Reg1
        .Pattern = "(\s[0-9]{4,6}\s)"
        .Global = True
    End With

    If Reg1.Test(Item.Body) Then
        Set M1 = Reg1.Execute(Item.Body)
        For Each M In M1
            Debug.Print M.SubMatches(0) ' Immediate Window

            '// allows for multiple matches in the message body
            Item.Subject = M.SubMatches(0) & "; " & Item.Subject

        Next
    End If

    Item.Save

    Set myForward = Item.Forward
    myForward.Recipients.Add "xxxxx@gmail.com"
    myForward.Display
End Sub

以下是我转发的新电子邮件主题的输出 SPORT - ,2017 SPORT - ,2017 SPORT - 5556我只想捕获“SPORT - 5556”

1 个答案:

答案 0 :(得分:2)

您可以使用否定前瞻(请参阅MSDN: "Regular Expression Syntax (Scripting)")从匹配项中排除某些字符串。

以下是我写这个的方法:

Option Explicit

Public Sub Forward(Item As Outlook.MailItem)
    Dim DigitsExp As New RegExp
    Dim Matches As MatchCollection, Match As Match

    If Item Is Nothing Then Exit Sub

    DigitsExp.Pattern = "\s(?!2017\s)([0-9]{4,6})\s"
    DigitsExp.Global = True

    Set Matches = DigitsExp.Execute(Item.Body)
    For Each Match in Matches
        Debug.Print Match.SubMatches(0)
        Item.Subject = Match.SubMatches(0) & "; " & Item.Subject
    Next
    If Not Item.Saved Then Item.Save

    With Item.Forward
        .Recipients.Add "xxxxx@gmail.com"
        .Display
    End With
End Sub

\s(?!2017\s)([0-9]{4,6})\s匹配任何不是2017的4-6位子字符串,(?!2017\s)是排除它的负前瞻。