Regex.Split() on comma, space or semi-colon delimi

2020-01-29 06:18发布

问题:

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"]

回答1:

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 than Regex.Split.

char[] delimiters = new [] { ',', ';', ' ' };  // List of your delimiters
var splittedArray = myString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);


回答2:

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:

var values = Regex.Split("22222, 11111, 23232", @"[\s,;]+")


回答3:

Regex.Split("22222, 11111, 23232", @"[ ,;]+")

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



回答4:

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:

@"[,;]\s*|\s+"

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:

@"[,;\s]+"

Of course, in that case, string.Split is a simpler option, as others have indicated.



回答5:

Try this Regex pattern:

([^,;\"\}\{\s*.]\d+)

For sample text:

{"123","456","789"}
1011,1213,1415
16, 17, 181920
212223;        242526;27
28 29 3031 

See demo.



标签: c# regex split