wouter de jong wouter de jong - 25 days ago 8
C# Question

How to get the last and first special chars of a string?

I got a few string in an list:

List<string> mylist = new List<string>();
mylist.Add("_+hello[]_");
mylist.Add("_+how||");
mylist.Add("_+are,,");
mylist.Add("||you=_");
mylist.Add("_+doing\"_");


I want to get the last and first special chars (+,_[]=") all in in array.

string[,] array = new string[5,2]


my array should look something like this on the end:

_+ AND [] _
_+ AND ||
_+ AND ,,
|| AND =_
_+ AND "_


Does anyone knows how to do this?

Thanks in advance

Answer

You seem to want to split with alphanumeric chars. Since \w matches alphanumeric or underscore chars, you can subtract the _ form it and use it with Regex.Split:

Regex.Split(str, @"[\w-[_]]+")

See this regex demo

Or

Regex.Split(str, @"[^\W_]+")

Here is a regex demo

The [^\W_] matches any char that is not a non-word char (that is, it matches any \w) and not a _ (so, any \w except _ that otherwise would get matched).