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

2020-01-29 06:00发布

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

标签: c# regex split
5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-01-29 06:11

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.

查看更多
成全新的幸福
3楼-- · 2020-01-29 06:15

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,;]+")
查看更多
欢心
4楼-- · 2020-01-29 06:19

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);
查看更多
劳资没心,怎么记你
5楼-- · 2020-01-29 06:21

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

查看更多
▲ chillily
6楼-- · 2020-01-29 06:34
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

查看更多
登录 后发表回答