VB.NET - 在复杂的字符串中提取引号内的文本

时间:2013-08-08 17:44:59

标签: vb.net string get extract

我有一个字符串看起来像这样:

a:391:i:0;s:12:"jnKKPkvpNnfn";i:1;s:12:"ic9VAk3PvQ3j";i:2;s:12:"PEBFuE6bGepr";i:3;s:12:"bwuxRkH6QbGp";i:4;s:12:"LSRDQbAKXc9q";i:5;s:12:"eLuVbSAxQCgo";}

我想在引文中找到文本并将它们发送到列表框。 我知道如何做到这一点,但是以一种无效的方式现在可以起作用......所以我要求提供一些如何做的建议。

由于

2 个答案:

答案 0 :(得分:0)

这应该让你开始;该方法将通过输入字符串运行并返回包含在引号内的字符串数组。

    string[] ParseQuotes(string input)
    {
        List<string> matches = new List<string>();
        bool open = false;
        int index = -1;

        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] == '"')
            {
                if (!open)
                {
                    open = true;
                    index = i;
                }
                else
                {
                    open = false;
                    string match = input.Substring(index + 1, index - i - 1);
                    matches.Add(match);
                }
            }
        }

        return matches.ToArray();
    }

转换为VB ...

Private Function ParseQuotes(input As String) As String()
    Dim matches As New List(Of String)()
    Dim open As Boolean = False
    Dim index As Integer = -1

    For i As Integer = 0 To input.Length - 1
        If input(i) = """"C Then
            If Not open Then
                open = True
                index = i
            Else
                open = False
                Dim match As String = input.Substring(index + 1, index - i - 1)
                matches.Add(match)
            End If
        End If
    Next

    Return matches.ToArray()
End Function

答案 1 :(得分:0)

在您的主要代码中:

cbYourcomboBox.Items.Clear()
cbYourcomboBox.Items.AddRange(GetList(str).ToArray)

然后是函数本身:

Public Function GetList(ByVal str As String) As List(Of String)
    Dim ar As String()
    Dim ar2 As List(Of String) = New List(Of String)
    ar = Split(str, Chr(34))

    ' making sure there is a matching closing quote with - (UBound(ar) And 1)
    For a As Integer = 1 To UBound(ar) - (UBound(ar) And 1) Step 2
        ar2.Add(ar(a))
    Next a

    Return ar2
End Function