Outlook VBA正则表达式提取电子邮件地址中的用户名

时间:2017-02-15 12:30:09

标签: vba outlook outlook-vba

如何从VBA中的电子邮件地址中提取用户名?

例如 - 如果我的电子邮件ID是“prateek@gmail.com”,那么用户名是“prateek”

到目前为止 - 我写了这个 -

Set Reg1 = New RegExp

' \s* = invisible spaces
' \d* = match digits
' \w* = match alphanumeric

With Reg1
    .Pattern = "\w+@gmail\.com"
    .Global = True
End With
If Reg1.Test(emailAddress) Then

    Set M1 = Reg1.Execute(emailAddress)
    For Each M In M1
        ' M.SubMatches(1) is the (\w*) in the pattern
        ' use M.SubMatches(2) for the second one if you have two (\w*)
        Debug.Print M.SubMatches(1)            
    Next
End If

但它看起来不像任何子匹配

1 个答案:

答案 0 :(得分:2)

尝试下面的代码,RegEx您可以使用LeftInstr结合使用。

Dim usern   As String

'emailAddress = "prateek@gmail.com" ' <-- for debug

usern = Left(emailAddress, InStr(emailAddress, "@") - 1)
MsgBox "UserName is " & usern