0

I'm trying to find a way of splitting a string that contains 2 {}{} brackets but after it's split it keeps the brackets.

Before word = {XXXX}{XXXX}

After

  • Word(1) = {XXXX}

  • word(2) = {XXXX}

I tried using split but this always removes the }{ which I want to keep. Somebody get me out of my misery!! I'm using vb.net.

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

4 Answers4

2

You can also try to use regular expressions.

    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
Edin Omeragic
  • 1,948
  • 1
  • 23
  • 26
0

This will work:

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
BanForFun
  • 752
  • 4
  • 15
  • Thanks BanForFun really appreciate your help. This worked perfect for me. –  Jul 16 '16 at 23:14
0

Here is a Linq way:

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

Here's another option using an iterator:

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

Output:

{hello}
{world}
Mark
  • 8,140
  • 1
  • 14
  • 29