如何拆分包含 {hello}{world} curley 括号但保留括号的字符串 (vb.net)

How to split a string containing {hello}{world} curley brackets but keep the brackets (vb.net)

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

词前 = {XXXX}{XXXX}

之后

我尝试使用 split,但这总是会删除我想保留的 }{。有人让我摆脱痛苦!!我正在使用 vb.net.

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

这会起作用:

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

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

    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

这是一个 Linq 方式:

    Dim brace As Char = "}"c
    Dim output As String() = (From s In input.Split(brace) 
        Where s <> String.Empty 
        Select s + brace).ToArray()

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

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}