Arrays VB2010从字符串或数组中提取数字字符串
我有一个文件路径,我想从文件路径的开头提取起始目录作业编号。除了我不知道如何从文件路径字符串中提取数字字符串。(即:filepath=Q:\2456_-blah_-blah\file.txt-或其他)我只想将“2456”作为字符串, 然后将该数字字符串放入我在表单上创建的TextBox2中。 到目前为止,我所使用的代码将输出一个“0”而不是所需的数字字符串。 任何帮助都将不胜感激Arrays VB2010从字符串或数组中提取数字字符串,arrays,vb.net,string,numbers,extract,Arrays,Vb.net,String,Numbers,Extract,我有一个文件路径,我想从文件路径的开头提取起始目录作业编号。除了我不知道如何从文件路径字符串中提取数字字符串。(即:filepath=Q:\2456_-blah_-blah\file.txt-或其他)我只想将“2456”作为字符串, 然后将该数字字符串放入我在表单上创建的TextBox2中。 到目前为止,我所使用的代码将输出一个“0”而不是所需的数字字符串。 任何帮助都将不胜感激 Private Sub Button1_Click(ByVal sender As System.Object,
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.OpenFileDialog1.FileName = Nothing
If Me.OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = Me.OpenFileDialog1.FileName
End If
If GetInfo() = True Then
For Each Xitem In ExcelRowList
Dim lvitem As ListViewItem
lvitem = Me.ListView1.Items.Add(Xitem.C1)
Next
End If
'''Here is where I call the GetFilePathOnly function
TextBox2.Text = GetFilePathOnly(TextBox1.Text)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
'''Section below is what defines my number string, then I call it above for the Button1.Click operation(towards the end)
Private Function GetFilePathOnly(ByVal Fullpath As String) As String
Dim File As String = Fullpath
Dim number As Double = Val(File)
Dim outcome As String = number.ToString 'File.Substring(0, File.LastIndexOf("\") + 1)
Return outcome
End Function
谢谢懒散的方法是使用拆分:
TextBox2.Text = path.Split("\")(1).Split("_")(0)
您还可以轻松地使用正则表达式
Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("Q:\2456_blah_blah\file.txt").Value
正则表达式是一个不错的选择。除非我将其更改为“
”^[A-Z]+\:\\.*\d+.*$”
正则表达式(“\d+”)做什么?我只是好奇。这是速记,意思是一行中的一个或几位数将是匹配的。danyim的版本更适合于您的示例字符串,并且更适合于精确匹配您想要的内容。假设我想从相同的文件名中获取“blah_blah”字符串,我可以使用类似于您输入的内容吗?我对正则表达式不熟悉。你想要什么样的文件名?他们会遵循什么规则,比如文件名前/后总是有数字?它们是否必须是一个接一个的,例如从“file_34567.txt”获取“34567”?或者您只是在寻找数字周期,例如从“34_5file_nam6e7.txt”中获取“34567”?“索引超出了数组的界限。”是我得到的错误吗