我正在尝试找到一种分割包含2 {} {}括号的字符串的方法,但在它拆分后保持括号。
在word = {XXXX} {XXXX}之前
之后
Word(1)= {XXXX}
字(2)= {XXXX}
我尝试使用拆分,但这总是删除} {我想要保留。有人让我摆脱了痛苦!我正在使用vb.net。
Dim word As String = "{hello}{world}"
Dim wordArr As String() = word.Split("}")
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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()
答案 3 :(得分: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}