我有10行数组,它们是名字空间姓氏空间邮政编码。所有邮政编码都以不同的数字开头。有没有办法替换下面索引中的#1,以便它搜索任何数字字符?
'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
答案 0 :(得分:1)
正则表达式允许您对文本进行模式匹配。它就像带有通配符支持的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
你可以用正则表达式非常精确地表达这一点:
^([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
要使代码编译,您必须在VB模块的顶部导入System.Text.RegularExpressions
命名空间,以获取Regex
和Match
类型。
如果输入数据采用不同的模式,则需要调整正则表达式。 例如,如果它可能是“Chris McElvoy III 29828”,那么您需要相应地调整正则表达式,以处理名称后缀。