I'm trying to split a string that can either be comma, space or semi-colon delimitted. It could also contain a space or spaces after each delimitter. For example
22222,11111,23232
OR
22222, 11111, 23232
OR
22222; 11111; 23232
OR
22222 11111 23232
Any one of these would produce an array with three values ["22222","11111","23232"]
So far I have var values = Regex.Split("22222, 11111, 23232", @"[\\s,;]+")
but this produces an array with the second and third values including the space(s) like so:
["22222"," 11111"," 23232"]
To interpret "I'm trying to split a string that can either be comma, space or semi-colon delimited. It could also contain a space or spaces after each delimiter" literally, try:
This has the property that consecutive delimiters (except white space) will not be treated as a single delimiter.
But if you want all consecutive delimiters to be treated as one, you might as well do:
Of course, in that case,
string.Split
is a simpler option, as others have indicated.You are using an
@
symbol for your string, so the"\"
is being interpreted as a literal slash. So your character class is actually reading as a"\"
, an"s"
, a","
or a";"
. Remove the extra slash and it should work as desired:You have two possibilities:
Regex.Split
String.Split
In this case, you want to split your string by specific delimiters caracters.
String.Split
has been created for this special purpose. This method will be faster thanRegex.Split
.Try this Regex pattern:
For sample text:
See demo.
this worked for me
Also check answer below, if all you really need is split a string based on few char delimiters - string.split is probably a better solution