Regex.Split(),以逗号,空格或分号分隔的字符串 [英] 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
其中任何一个都会产生一个数组具有三个值 [ 22222, 11111, 23232]
Any one of these would produce an array with three values ["22222","11111","23232"]
到目前为止,我有 var值= Regex.Split( 22222,11111,23232,@ [\\s,;] +)
但这会生成一个包含第二个和第三个数组包括空格的值,如下所示:
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"]
推荐答案
您有两种可能:
Regex.Split
String.Split
在在这种情况下,您想按特定的定界符分割字符串。为此目的创建了 String.Split
。此方法将比 Regex.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);
这篇关于Regex.Split(),以逗号,空格或分号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!