suchanoob
suchanoob

Reputation: 300

Get value between strings in RichTextBox

I have a richtextbox filled with some text (e.g. [mplampla], [randomstring], [string]...). The richtextbox has many lines. I'm trying to get every value between "[" and "]" but I can't.

That's my code so far:

For Each line In RichTextBox1.Lines
        Dim string1 As String = line
        Dim finalstring As String = ""
        finalstring = string1.Split("[")(1).Split("]")(0)
        MsgBox(finalstring)
    Next

Upvotes: 1

Views: 1477

Answers (3)

valverij
valverij

Reputation: 4941

You can do this pretty quickly with regular expressions using positive lookarounds:

(?<=\[)(\w|\s)*(?=\])

Consider the following console app:

Dim str = "this is [my] string [with some] [brackets]"
Dim pattern = "(?<=\[)(\w|\s)*(?=\])"
Dim matches = System.Text.RegularExpressions.Regex.Matches(str, pattern)

For Each match In matches
    Console.WriteLine(match)
Next

Which results in this output:

my
with some
brackets

Also, you could expand that to match multiline text by using the Regex.Matches(String, String, RegexOptions) overload:

RegularExpressions.Regex.Matches(str, pattern, RegexOptions.Multiline)

Upvotes: 1

LarsTech
LarsTech

Reputation: 81610

I don't think you can get all the values inside the brackets by using a String.Split.

Regex is good at these things, but you can also just use the IndexOf function to find the brackets:

Dim words As New List(Of String)
Dim startIndex As Integer = 0
While startIndex > -1
  startIndex = rtb.Text.IndexOf("[", startIndex)
  If startIndex > -1 Then
    Dim endIndex As Integer = rtb.Text.IndexOf("]", startIndex)
    If endIndex > -1 Then
      words.Add(rtb.Text.Substring(startIndex + 1, endIndex - startIndex - 1))
    End If
    startIndex = endIndex
  End If
End While
MessageBox.Show(String.Join(Environment.NewLine, words.ToArray))

Upvotes: 2

Hoh
Hoh

Reputation: 1184

Try like this

    For Each line In RichTextBox1.Lines
                Dim string1 As String = line
                Dim betastring As String = ""
                Dim finalstring As String = ""
                betastring = string1.Split("[")(1)
                finalstring = betastring .Split("]")(0)
                MsgBox(finalstring)
            Next

Upvotes: 1

Related Questions