wouter de jong wouter de jong - 5 months ago 24
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>();

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


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


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).