Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I try to get all matches between two commas (","). I have so far a code but it isnt working as i expect it. The text to be searched in is the RichTextBox.Text Property.

For example i write ,5,9,12,17,4,8,11, and my regex code returns ,5,|,12,|,4,|,11,
I know what the code is doing, it is searching A-B, C-D, E-F, but i need something like A-B, B-C, C-D etc. How to modify it to return all values

VB
Me.Text = ""
Dim regex As New Regex("\,(.*?)\,")

For Each m As Match In regex.Matches(RichTextBox1.Text)
    Me.Text += m.Value & "|"
Next


What I have tried:

----------------------------------------------------
Posted
Updated 4-Mar-16 6:09am
v3

Your pattern currently consumes the leading and trailing commas, so every other value is skipped.

You need to use zero-width positive lookahead/lookbehind assertions instead:
Regular Expression Language - Quick Reference[^]

Also, it would be better to use [^\,]* rather than .*?, since you know you want to match anything except a comma.

And finally, if you're doing string concatenation in a loop, you should use a StringBuilder instead.
VB.NET
Dim regex As New Regex("(?<=\,)([^\,]*)(?=\,)")
Dim sb As New System.Text.StringBuilder()

For Each m As Match in regex.Matches(RichTextBox1.Text)
    sb.Append(m.Value)
    sb.Append("|")
Next

Me.Text = sb.ToString()
 
Share this answer
 
v2
Comments
[no name] 4-Mar-16 12:52pm    
Thanks, worked like a charm. Thanks
This isn't mine, but I forget where I got it (it was sitting in my "useful regexes" collection under "split CSV data")
(?:^|,)(?=[^"]|(")?)"?((?(1)[^"]*|[^,"]*))"?(?=,|$)

Me? I'd use String.Split on the comma, and discard empty values rather than use a regex.
 
Share this answer
 
Comments
[no name] 4-Mar-16 12:49pm    
I know, but i have to use regex for the reason that i have to keep track of the match index. I have to color specific values while dealing with Richtextbox Select(index, length).
Sorry for me being a noob, i tried this "(?:^|,)" and it was catching the two endpoint commas, thus leaving no tag to catch the remaining ones. Thank you.
It is easier (and faster) to split the string at comma as OriginalGriff said.
 
Share this answer
 
Comments
[no name] 4-Mar-16 12:52pm    
I have to use regex to catch the tag.index which i use to color certain richtextbox text. Its of greater importance to use regex in my case. Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900