0

我正在尝试找到一种拆分包含 2 个 {}{} 括号的字符串的方法,但在拆分后它会保留括号。

字前 = {XXXX}{XXXX}

  • 字(1)= {XXXX}

  • 字(2)= {XXXX}

我尝试使用 split 但这总是删除我想保留的 }{ 。有人把我从痛苦中解救出来!!我正在使用 vb.net。

Dim word As String = "{hello}{world}" 
Dim wordArr As String() = word.Split("}")
4

4 回答 4

2

您也可以尝试使用正则表达式。

    Dim pattern As New Regex("(?<Word1>\{\w+\})(?<Word2>\{\w+\})")
    Dim match = pattern.Match("{Hello}{World}")

    Dim word1 = match.Groups("Word1").Value
    Dim word2 = match.Groups("Word2").Value
于 2016-07-13T17:07:28.427 回答
0

这将起作用:

Dim word As String = "{hello}{world}"
    Dim wordArr As String() = word.Split({"}"}, StringSplitOptions.RemoveEmptyEntries)
    Dim lst1 As New List(Of String)
    For Each l In wordArr
        lst1.Add(l & "}")
    Next
    wordArr = lst1.ToArray
于 2016-07-13T17:04:35.757 回答
0

这是一种Linq方式:

    Dim brace As Char = "}"c
    Dim output As String() = (From s In input.Split(brace) 
        Where s <> String.Empty 
        Select s + brace).ToArray()
于 2016-07-13T17:28:15.930 回答
0

这是使用迭代器的另一个选项:

Public Iterator Function SplitAfter(input As String, delim As Char) As IEnumerable(Of String)
    Dim sb As StringBuilder = New StringBuilder(input.Length)
    For Each c As Char In input
        sb.Append(c)
        If c = delim Then
            Yield sb.ToString()
            sb.Clear()
        End If
    Next
    If sb.Length > 0 Then
        Yield sb.ToString()
    End If
End Function

Dim word As String = "{hello}{world}"
Dim wordArr As String() = SplitAfter(word, "}"c).ToArray()
For Each w As String In wordArr
    Console.WriteLine(w)
Next

输出:

{hello}
{world}
于 2016-07-13T19:50:31.107 回答