Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String by logicals with Regex

Tags:

c#

.net

regex

I've the following string:

string text = "Hello && my || Name & is | Tom"

Now I want to split the string into different parts without the logical operators between the words. I've tried the following, but I get only one string with the whole text.

String[] result= Regex.Split(text, @"\&&\||\&\|");

Whats wrong?

The expected output is an array with 5 strings:

  • Hello
  • my
  • Name
  • is
  • Tom
like image 687
Maddy Avatar asked Sep 13 '26 16:09

Maddy


2 Answers

No regex solution, just splitting:

String[] result = text.Split(new Char[] { '|', '&' }, StringSplitOptions.RemoveEmptyEntries);
like image 95
Dmitry Bychenko Avatar answered Sep 15 '26 06:09

Dmitry Bychenko


Change your code to,

String[] result= Regex.Split(text, @"\s*[|&]+\s*");

This splits your input according to one or more | or & symbols. \s* matches zero or more spaces , and [|&]+ matches one or more | or & symbols.

like image 41
Avinash Raj Avatar answered Sep 15 '26 06:09

Avinash Raj