Ishaan Patel
Ishaan Patel

Reputation: 61

Need To Extract String After '@' & Before ' ' (Blank Space) Multiple Times

I'm working on extracting twitter/facebook style mentions from a textbox. So far, here's my code:

  Dim a As String = TextBox1.Text + " "
        Dim b As Char() = a.ToCharArray
        Dim c As String
        Dim l As Integer = TextBox1.Text.Length
        Dim temp As Integer = 0
        Dim nex As Integer = a.IndexOf(" ")
        For i = 0 To l - 1

            If b(i) = "@" Then
                temp = 1
            ElseIf temp = 1 Then
              temp = 2
            End If

            If temp = 2 Then

                c = a.Substring(i, nex).Trim() 'nex needs be replaced with next space on 2nd or nth loop
                MsgBox(c)
                temp = 0
                nex = a.IndexOf(" ") + nex
            End If

        Next

Now this works great if the entered text is- @one @twwo @three. (If the next strings are greater in length.) But doesn't work elsewhere.

Also, there is probably going to be content between two @mentions so I'm not willing to change the b(i).

I'm sure there's a much more efficient way to do this. Thanks!!

Upvotes: 1

Views: 287

Answers (1)

Bradley Uffner
Bradley Uffner

Reputation: 16991

This is a job for regex. The pattern @\w+ should do nicely.

For Each m As Match In Regex.Matches("@testing this is a @test", "@\w+")
    Console.WriteLine(m.Value)
Next

Will print out @testing and @test.

This pattern basically means "Find everything that starts with an '@' followed by one or more 'word characters'."

Regex is a very powerful tool for searching strings, you can read more about it on MSDN.

Upvotes: 1

Related Questions