0

有没有办法指定我想从数组字符串中提取哪些字符?这不是,下面的代码,论坛只是不喜欢它作为文本。

For example:  abc1234blahblah  and I want to point from the left, characters [4-7] 
Character 4 = "1"
Character 5 = "2"
Character 6 = "3"
Character 7 = "4"

然后我想把它们放到一个字符串中:“1234”

我正在处理的真正应用程序,文件路径的第一个目录始终以项目编号开头,因此我想提取作业编号并将其放入 VB 2010 的文本框中。示例:Q:\2456_customer_name....\ file.xls 我希望能够再次指向数字,但是如果我知道主目录将始终以作业编号开头,那么我应该能够仅指向字符 [4-7] 并将其放入一个字符串。我想我知道这个概念,但对 VB 的了解还不够,无法将其组合在一起。

任何帮助将非常感激。

4

2 回答 2

1

您可以使用Substring 函数

Dim a = "abc1234blahblah"
Dim b = a.Substring(3, 4) ' b now contains "1234"

再想一想,文件所在的驱动器是否有可能像 UNC 路径一样\\MyServer\SomeShare\9876_CustomerName\file.xls?如果是这样,提取数字会有点棘手。我试图说明指定文件的所有可能方式:

Module Module1

    Function GetCustomerNumber(filename As String) As String
        Dim abspath = IO.Path.GetFullPath(filename)
        Dim dir = IO.Path.GetDirectoryName(abspath)
        Dim fileParentDirectory = dir.Split(IO.Path.DirectorySeparatorChar).Last
        Return fileParentDirectory.Substring(0, 4)
    End Function

    Sub Main()

        Dim a = "C:\5678_CustomerName\file.xls"
        Dim b = "\\se1234\Share001\5678_CustomerName\file.xls"
        Dim c = "\5678_CustomerName\file.xls"
        Dim d = ".\5678_CustomerName\file.xls"
        Dim e = "5678_CustomerName\file.xls"
        Console.WriteLine(GetCustomerNumber(a))
        Console.WriteLine(GetCustomerNumber(b))
        Console.WriteLine(GetCustomerNumber(c))
        Console.WriteLine(GetCustomerNumber(d))
        Console.WriteLine(GetCustomerNumber(e))

        Console.ReadLine()

    End Sub

End Module

它为所有示例输出“5678”。

于 2012-10-19T17:27:31.850 回答
0

正则表达式会起作用

Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("abc1234blahblah").Value
于 2012-10-19T17:39:24.257 回答