VB2010从字符串或数组中提取一串数字

时间:2012-10-19 16:14:08

标签: 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, 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

由于

2 个答案:

答案 0 :(得分:0)

懒惰的方式是使用Split:

TextBox2.Text = path.Split("\")(1).Split("_")(0)

答案 1 :(得分:0)

您也可以轻松使用正则表达式。

Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("Q:\2456_blah_blah\file.txt").Value