2017-02-15 148 views
1

如何從VBA中的電子郵件地址提取用戶名?Outlook VBA正則表達式提取電子郵件地址中的用戶名

例如 - 如果我的電子郵件ID是 「[email protected]」,那麼用戶名是 「prateek」

到目前爲止 - 我寫了這一點 -

Set Reg1 = New RegExp 

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

With Reg1 
    .Pattern = "\[email protected]\.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 

但它並不像它去任何submatch

+2

正則表達式是沒有必要在這裏,你可以使用左,與InStr函數尋找@ –

+0

@ShaiRado:哎呀,我打字^^ – R3uK

回答

2

請嘗試下面的代碼,RegEx insread你可以使用Left結合Instr

Dim usern As String 

'emailAddress = "[email protected]" ' <-- for debug 

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

比'Regexp'更好!但會建議字符串函數左$超過其變種表兄左 – brettdj

相關問題