2011-05-01 68 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”,那么您需要相应地调整正则表达式来处理名称后缀。