bflemi3
bflemi3

Reputation: 6790

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

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

Upvotes: 21

Views: 44212

Answers (5)

Cédric Bignon
Cédric Bignon

Reputation: 13022

You have two possibilities:

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

Upvotes: 39

GRUNGER
GRUNGER

Reputation: 496

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.

enter image description here

Upvotes: 0

Ani
Ani

Reputation: 113402

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.

Upvotes: 1

JDB
JDB

Reputation: 25810

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,;]+")

Upvotes: 8

Aleksei Poliakov
Aleksei Poliakov

Reputation: 1332

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

Upvotes: 2

Related Questions