|
-
Aug 16th, 2007, 01:49 PM
#1
Thread Starter
Hyperactive Member
[2005] help with parsing
what is the best way to parse out items in a textbox?
i need to capture all the values between []
example:
Hello [name]
Blah blah blah [place]
Thank you.
[user]
This is what i'm trying with no luck
Code:
Dim sMsgBody As String = Me.TextBox1.Text
Dim split As String() = sMsgBody.Split(New [Char]() {"["c, "]"c})
Dim s As String
For Each s In split
If s.Trim() <> "" Then
Console.WriteLine(s)
End If
Next s
-
Aug 16th, 2007, 02:21 PM
#2
Re: [2005] help with parsing
Here you go...
Code:
Option Strict On
Imports system.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim matches As MatchCollection = Regex.Matches(TextBox1.Text, "\[.*?\]")
Dim TextItems As New ArrayList
For i As Integer = 0 To matches.Count - 1
TextItems.Add(matches(i).ToString.Replace("[", String.Empty).Replace("]", String.Empty))
MessageBox.Show(TextItems(i).ToString)
Next
End Sub
End Class
If the text items can be split over multiple lines then use;
Code:
Dim matches As MatchCollection = Regex.Matches(TextBox1.Text, "\[.*?\]", RegexOptions.Singleline)
and also use
Code:
TextItems.Add(matches(i).ToString.Replace("[", String.Empty).Replace("]", String.Empty).Replace(ControlChars.NewLine, String.Empty))
Last edited by Bulldog; Aug 16th, 2007 at 02:29 PM.
-
Aug 16th, 2007, 02:57 PM
#3
Re: [2005] help with parsing
You can use Regex.
Try this
Code:
Dim input As String = "Hello [Mike], how[are]you doing[?]"
Dim pattern As String = "(?<=\[).*?(?=\])"
Dim matches As System.Text.RegularExpressions.MatchCollection
matches = System.Text.RegularExpressions.Regex.Matches(input, pattern)
For Each m As System.Text.RegularExpressions.Match In matches
MessageBox.Show(m.Value)
Next
-
Aug 16th, 2007, 03:22 PM
#4
Thread Starter
Hyperactive Member
Re: [2005] help with parsing
in the pattern (?<=\[).*?(?=\])
the items between ) ( are not skipped?
start: (?<=\'Start Value')
end: (?=\'End Value')
ignore: ) ignore contents (
am i close to understanding this?
-
Aug 16th, 2007, 04:13 PM
#5
Re: [2005] help with parsing
(?<=XXX) means to include this prefix (XXX) in the search but do not add it to the result.
(?=XXX) means to include this suffix (XXX) in the search but do not add it to the result
So the end result is what in between the prefix and suffix.
The \ is just the escape character since the squared brackets are special characters used by regex, so you have to use the escape char to let it know that it should treat the [ and ] as literals.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|