2013-04-07 57 views
0

我有我想用來比較兩個字符串的代碼。這個想法是獲得一個單詞的第一個字母和一個數字的最後四個字母,並將它們放在一起,以便我可以將它與另一個字母進行比較。例如,如果我有「史密斯約翰123456」,我想輸入「s3456」,我應該能夠找到它。如何獲得最後四位和第一個字符?

Dim strFileName, strTxtValue 

strFileName = "4ABCD_Delta_Jhon_T_JR_123456" 
strTxtValue = "D3456" 

Dim item, items, firstInitial, lastFour, myArray 

strFileName = replace(strFileName,"_"," ") 
myArray = Split(strFileName) 

For Each item In myArray 
    If IsNumeric(item) Then 
     lastFour = Right(item, Len(item)-2) 
     Exit For 
    End If 
Next 
For Each items In myArray 
    firstInitial = Left(items, 1)&lastFour 
    If UCase(strTxtValue) = UCase(firstInitial) Then 
     Contains = True 
    End If 
Next 

到目前爲止,這是我的,但我無法使它工作。有人能幫幫我嗎?

+1

的右項目的最多四個字符是「Right(item,4)」。 – phatfingers 2013-04-07 11:57:24

回答

1

另一種替代方法:

strFileName = "4ABCD_Delta_Jhon_T_JR_123456" 
strTxtValue = "D3456" 
strFromName = "" 
myArray  = Split(strFileName, "_") 
For i = 0 To UBound(myArray) 
    firstChar = Asc(myArray(i)) 
    'if not a number... 
    If firstChar < 48 Or firstChar > 57 Then 
     strFromName = Chr(firstChar) 
     Exit For 
    End If 
Next 
strFromName = strFromName & Right(strFileName, 4) 
WScript.Echo strFromName, CStr(strFromName = strTxtValue) 
'>> D3456 True 
+0

這正是我在尋找的謝謝你,並感謝其他人你們搖滾 – user1766952 2013-04-07 23:36:13

2

鑑於你的第一個例子中,得到的第一個字母和最後四位數字是很容易:

>> s = "Smith John 123456" 
>> t = LCase(Left(s, 1)) & Right(s, 4) 
>> WScript.Echo t, CStr(t = "s3456") 
>> 
s3456 True 

如果您的輸入更加多元化,例如例如「4ABCD_Delta_Jhon_T_JR_123456」, 等文件名,則可能需要使用RegExp或Split的創意用途。讓我們先從:

>> s = "4ABCD_Delta_Jhon_T_JR_123456" 
>> s = Split(s, "_", 2)(1) 
>> t = LCase(Left(s, 1)) & Right(s, 4) 
>> WScript.Echo t, CStr(t = "d3456") 
>> 
d3456 True 
>> 

這顯然取決於名稱是輸入的第二個塊。

如果您提供了一些更具代表性的輸入樣本,我願意考慮RegExp解決方案。

+0

謝謝ekkehard我的問題是s可能是「4ABCD_Delta_Jhon_T_JR_123456」或這個「Delta_Jhon_T_JR_123456」 – user1766952 2013-04-07 22:52:25

1

另一種方法是使用一個正則表達式的:

s = "Smith John 123456" 

Set re = New RegExp 
re.Pattern = "^(.).*(.{4})$" 

WScript.Echo LCase(re.Replace(s, "$1$2")) 

和用於第二實施例是這樣的:

s = "4ABCD_Delta_Jhon_T_JR_123456" 

Set re = New RegExp 
re.Pattern = "^(?:\w*?[0-9]\w*?_)?([a-z])[a-z]*_.*(.{4})$" 
re.IgnoreCase = True 

WScript.Echo LCase(re.Replace(s, "$1$2")) 
+0

謝謝ansgar我嘗試使用正則表達式,但s值可以是s =「4ABCD_Delta_Jhon_T_JR_123456」或s =「Delta_Jhon_T_JR_123456 「,那麼你怎麼做 – user1766952 2013-04-07 22:53:30

+0

查看更新的答案。 – 2013-04-08 08:30:15

相關問題