VB.NET:确定输入文本字符串中的分隔符

时间:2014-12-17 20:18:39

标签: vb.net string text textbox delimiter

有没有办法主动扫描文本框以搜索键分隔符?我正在寻找分隔符:vbNewLine,逗号,冒号,分号和空格。

一旦用户粘贴了分隔的字符串,我怎样才能让VB.net确定哪个字符是分隔的呢?

示例:

输入字符串:“aaa,bbb,ccc”

我希望能够扫描该文本并知道分隔符是“,”

同样的“aaa; bbb; ccc”,将是“;”

分隔符之间可以是任意数量的值

1 个答案:

答案 0 :(得分:3)

您可以使用以下类,ClosestDelimiter为您提供最有可能匹配的分隔符(如果它没有找到它正在寻找的内容,它将抛出一个错误,请注意:))

我还添加了一个Parse方法,该方法返回单个项目的数组(如果分隔符直接在前一个分隔符后出现,则可以包含空字符串,例如:; A ;; C ;; D)

最后一个TryParse方法,返回true或false,并为您捕获异常,解析失败时更新结果为Nothing

Public Class DelimiterScanner
    Private delimiters() As String = {vbNewLine, ",", ";", ":", " "}

    Public Function ClosestDelimiter(row As String) As String
        Dim maxUsages As Integer = 0
        Dim multiplePossibilities As Boolean = False
        Dim current As Integer
        Dim delimiter As String = Nothing

        If String.IsNullOrWhiteSpace(row) Then
            Throw New ArgumentException("Row cannot be an empty string", "row")
        End If

        For Each del As String In delimiters
            current = row.Split({del}, StringSplitOptions.None).Count
            If current > maxUsages Then
                delimiter = del
                maxUsages = current
                multiplePossibilities = False
            ElseIf current > 0 AndAlso current = maxUsages Then
                multiplePossibilities = True
            End If
        Next
        If multiplePossibilities Then
            Throw New FormatException("Multiple delimiters have the same length")
        End If
        If maxUsages = 0 Then
            Throw New FormatException("No delimiters found in row")
        End If
        Return delimiter
    End Function

    Public Function Parse(row As String, Optional useDelimiter As String = Nothing) As String()
        Dim selectedDelimiter As String = useDelimiter
        Dim result() As String = Nothing

        If String.IsNullOrWhiteSpace(row) Then
            ' don't parse empty strings
            Throw New ArgumentException("Cannot parse an empty input value", row)
        End If
        If String.IsNullOrWhiteSpace(selectedDelimiter) Then
            ' get delimiter if no basic is given
            selectedDelimiter = ClosestDelimiter(row)
        End If
        result = row.Split({selectedDelimiter}, StringSplitOptions.None)

        Return result
    End Function

    Public Function TryParse(row As String, ByRef result() As String, Optional useDelimiter As String = Nothing) As Boolean
        Dim succeeded As Boolean = True

        Try
            result = Parse(row, useDelimiter)
        Catch ex As Exception
            result = Nothing
            succeeded = False
        End Try
        Return succeeded

    End Function
End Class

<强>更新

例如,您可以使用这样的类(在这里您可以看到我的控制台类的主要方法)。我们首先启动new类,然后使用TryParse方法检查它是否可解析,否则,解析无效,并且无法确定分隔符。如果它有效,您可以调用ClosestDelimiter方法,并且您还可以假设您的结果包含正确的字符串。

我还在SplitMethod上做了更新,因为我必须考虑到我们要分割字符串,而不是在单独的字符上(例如:VbNewLine),我也在上面的代码中纠正了这个

Sub Main()
    Dim dScanner As New DelimiterScanner()
    Dim result() As String = Nothing
    Dim tests() As String = {String.Empty, "a,b;c", "aaa,bbb,ccc;", "a;b;c;;;;d", "this is a test;working;online;stackoverflow;", "aaa" + vbNewLine + "bbb" + vbNewLine + "ccc"}

    For Each testItem In tests
        Console.WriteLine("Trying to parse {0}", testItem)
        If dScanner.TryParse(testItem, result) Then
            Console.WriteLine(vbTab & "- Results (joined with ,): {0}", String.Join(",", result))
            Console.WriteLine(vbTab & "- Used delimited: {0}", dScanner.ClosestDelimiter(testItem))
        Else
            Console.WriteLine(vbTab & "- Delimiter cannot be found!")
        End If
    Next
    Console.ReadLine()
End Sub

然后输出如下:

Trying to parse
        - Delimiter cannot be found!
Trying to parse a,b;c
        - Delimiter cannot be found!
Trying to parse aaa,bbb,ccc;
        - Results (joined with ,): aaa,bbb,ccc;
        - Used delimited: ,
Trying to parse a;b;c;;;;d
        - Results (joined with ,): a,b,c,,,,d
        - Used delimited: ;
Trying to parse this is a test;working;online;stackoverflow;
        - Results (joined with ,): this is a test,working,online,stackoverflow,
        - Used delimited: ;
Trying to parse aaa
bbb
ccc
        - Results (joined with ,): aaa,bbb,ccc
        - Used delimited:

希望这会有所帮助:)