2017-02-15 9 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 

しかし、それはのように見えるdoesntのそれはすべてのサブマッチを行く

+2

正規表現は、あなたは、InStr関数は、@ –

+0

@ShaiRadoを探していると、左を使用することができ、ここでは必要ありません:くそー、私は入力した^^ – R3uK

答えて

2

RegExの広範なとInstrを組み合わせて使用​​することができますの下のコードを試してみてください。

Dim usern As String 

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

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

Regexp' 'よりも良いです!。しかし、その異端のいとこの上に文字列関数Left $を提案する – brettdj