Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex .net split

I can split a string into two based on 2 spaces:

string Line = "1  2";

Regex.Split(Line, "  ");

=> 1, 2

I would like to add an exception. Only split if 'not enclosed by [ ]' as shown in this example.

string Line = "1  2  [1  2]";

Regex.Split(Line, "  ");

=> 1, 2, [1 2]

Can I fairly easily achieve this via regex? By the way, I use .NET.

like image 428
cs0815 Avatar asked May 03 '26 06:05

cs0815


1 Answers

You could use a lookahead, that asserts that there is no closing ] before the next opening [ or the end of the string:

Regex.Split(Line, @"[ ]+(?![^\[\]]*\])");

This will fail you if you have nested [...] structures though. Note that the lookahead is not part of the actual match, it just checks what follows without consuming anything. Inside the lookahead I used [^\[\]] which is a negated character class, matching any character except for any kind of square bracket.

Also note that this splits on 1 or more spaces. If you want to require at least two, replace [ ]+ with [ ]{2,} and if you want exactly two with [ ]{2}.

Further reading on lookarounds.

like image 200
Martin Ender Avatar answered May 04 '26 19:05

Martin Ender



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!