2011-05-01 69 views
0

我有10行數組是第一個名字空間的姓氏空間郵政編碼。所有的郵政編碼都以不同的數字開頭。有沒有辦法在下面的indexof中替換#1,以便它搜索任何數字字符?VB.net有關數組搜索的問題

'open file 
    inFile = IO.File.OpenText("Names.txt") 

    'process the loop instruct until end of file 
    intSubscript = 0 
    Do Until inFile.Peek = -1 OrElse intSubscript = strLine.Length 

     strLine(intSubscript) = inFile.ReadLine 
     intSubscript = intSubscript + 1 
    Loop 

    inFile.Close() 

    intSubscript = 0 
    strFound = "N" 

    Do Until strFound = "Y" OrElse intSubscript = strLine.Length 
     intIndex = strLine(intSubscript).IndexOf("1") 
     strName = strLine(intSubscript).Substring(0, intIndex - 1) 
     If strName = strFullname Then 
      strFound = "Y" 
      strZip = strLine(intSubscript).Substring(strLine(intSubscript).Length - 5, 5) 
      txtZip.Text = strZip 
     End If 
    Loop 

End Sub 
+1

您應該使用'Boolean'而不是'strFound'。 – SLaks 2011-05-01 16:16:34

回答

1

使用regular expression

正則表達式允許您對文本進行模式匹配。這就像String.IndexOf()和通配符支持。

例如,假設您的源數據是這樣的:

James Harvey 10939 
Madison Whittaker 33893 
George Keitel 22982 

...等等。

的英文表達,每一行後面的模式是這樣的:

the beginning of the string, followed by 
a sequence of 1 or more alphabetic characters, followed by 
a sequence of one or more spaces, followed by 
a sequence of 1 or more alphabetic characters, followed by 
a sequence of one or more spaces, followed by 
a sequence of 5 numeric digits, followed by 
the end of the string 

您可以表達非常準確,succintly在正則表達式是這樣的:

^([A-Za-z]+) +([A-Za-z]+) +([0-9]{5})$ 

這種方式將它應用在VB:

Dim sourcedata As String = _ 
     "James Harvey 10939" & _ 
     vbcrlf & _ 
     "Madison Whittaker 33893" & _ 
     vbcrlf & _ 
     "George Keitel 22982" 

    Dim regex = "^([A-Za-z]+) +([A-Za-z]+) +([0-9]{5})$" 

    Dim re = New Regex(regex) 

    Dim lineData As String() = sourceData.Split(vbcrlf.ToCharArray(), _ 
               StringSplitOptions.RemoveEmptyEntries) 

    For i As Integer = 0 To lineData.Length -1 
     System.Console.WriteLine("'{0}'", lineData(i)) 
     Dim matchResult As Match = re.Match(lineData(i)) 
     System.Console.WriteLine(" zip: {0}", matchResult.Groups(3).ToString()) 
    Next i 

要獲得該代碼進行編譯,您必須導入System.Text.RegularExpressions nam在VB模塊的頂部使用空格,以獲得RegexMatch類型。

如果你的輸入數據遵循不同的模式,那麼你將需要調整你的正則表達式。 例如,如果它可能是「Chris McElvoy III 29828」,那麼您需要相應地調整正則表達式來處理名稱後綴。