我正在尝试找到一种拆分包含 2 个 {}{} 括号的字符串的方法,但在拆分后它会保留括号。
字前 = {XXXX}{XXXX}
后
字(1)= {XXXX}
字(2)= {XXXX}
我尝试使用 split 但这总是删除我想保留的 }{ 。有人把我从痛苦中解救出来!!我正在使用 vb.net。
Dim word As String = "{hello}{world}"
Dim wordArr As String() = word.Split("}")
我正在尝试找到一种拆分包含 2 个 {}{} 括号的字符串的方法,但在拆分后它会保留括号。
字前 = {XXXX}{XXXX}
后
字(1)= {XXXX}
字(2)= {XXXX}
我尝试使用 split 但这总是删除我想保留的 }{ 。有人把我从痛苦中解救出来!!我正在使用 vb.net。
Dim word As String = "{hello}{world}"
Dim wordArr As String() = word.Split("}")
您也可以尝试使用正则表达式。
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
这将起作用:
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
这是一种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}