首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VBA正则表达式

VBA正则表达式
EN

Stack Overflow用户
提问于 2017-01-20 13:36:12
回答 1查看 136关注 0票数 0

我试图通过一个电子邮件主体和转发电子邮件到一个不同的收件箱。我有我的Regex匹配任何4-6字符号码与空白前后,但问题是日期包括在电子邮件中,所以它是接四个字符号码"2017“。是什么是Regex省略了"2017“,只取所有其他4-6字符数字。这是我的密码。

代码语言:javascript
复制
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

这是我的输出在我的新电子邮件的主题,我正在转发。

体育-2017年体育-2017年体育- 5556我只想能够捕捉到“体育- 5556”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-20 13:56:54

您可以使用负前瞻性(参见MSDN:“正则表达式语法(脚本)” )从匹配中排除某些字符串。

下面是我写这个的方法:

代码语言:javascript
复制
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)则是排除它的负前瞻。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41764979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档