Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex split with exceptions

Tags:

c#

.net

regex

This is an extension to this SO question. This question considers two different enclosing characters, in contrast to the original question.

I would like to split by (white)spaces of any number but ignore everything between <> AND "". So this string:

string Line = "1  2  <1  2> \"hello world\"   3";

Should result in this:

1, 2, <1 2>, \"hello world\", 3

like image 357
cs0815 Avatar asked Sep 14 '26 14:09

cs0815


1 Answers

Instead of Split, I'll use Matches

string Line = "1  2  <1  2> \"hello world\"   3";
var parts = Regex.Matches(Line, @"[<\""]{1}[\w \d]+?[>\""]{1}|[\w\d]+")
                 .Cast<Match>()
                 .Select(m=>m.Value)
                 .ToArray();

PS: This would also match "abc def>. But I ignored it to make the regex shorter

like image 88
L.B Avatar answered Sep 16 '26 04:09

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!