2016-11-15 61 views
-2

我想将字符串拆分为3部分。比如我有一个的电子邮件地址一样VBA正则表达式邮件

[email protected] 

,我想将它拆分成

testuser 
gamil 
.com 

与左,右和中(STR)我如果是固定lenght只能提取字符串。 有没有人提出一些想法?

+0

HTTP ://stackoverflow.com/documentation/vba/3480/searching-within-strings-for-the-presence-of-substrings#t=20161115192324085467 –

回答

0

leftrightmid(STR)如果是固定长度i仅可以提取的字符串。

这不是真的,因为你也可以使用len函数来获取字符串的长度。

Dim L as Integer 
L = Len("[email protected]") 
MsgBox L 

您还可以使用Instr(和InstrRev,逆转)函数找到特定字符或字符串的索引。

Dim I as Integer 
I = Instr("[email protected]", "@") 

因此,对于你的情况,没有正则表达式自定义函数将返回的三个项目的数组:

Function SplitEmail(email$) 
'Function returns an array like: 
' {"username", "domain", "tld"} 

Dim Dot As Integer, At As Integer 
Dot = InStrRev(email, ".") 
At = InStr(email, "@") 

Dim ret(1 To 3) As String 

ret(1) = Left(email, At - 1) 
ret(2) = Mid(email, At + 1, Dot - At - 1) 
ret(3) = Mid(email, Dot + 1) 

SplitEmail = ret 

End Function 

来获取用户名的一部分,你可以这样做:

Dim some_email$ 
some_email = "[email protected]" 

MsgBox SplitEmail(some_email)(1)