Regex.Split关于特定字符

时间:2015-05-15 18:56:17

标签: c# regex regex-negation

我试图在包含Non Word Characters (\W)的所有spaces上进行字符串拆分,但包括以下字符:.,{{1} },_。我也试图保持 $ 除{/ 1>}以外的任何分隔符

我怎么能这样做?我读了许多问题,但这没有意义。这是我的最新代码:

Regex.Split

编辑:

这里的一个例子

spaces

我想:

string[] result = Regex.Split (source, @"(\W[^(.|_|#|$)])"); _ using System.Text; _ using

(当前)结果是:

System.Text _ ; _ _ _ using _ System.Text

2 个答案:

答案 0 :(得分:2)

您可以使用以下特定于.NET的[\W-[._$#\s]])|\s+正则表达式,并利用C#LINQ删除空数组项:

var txt = "      using System.Text;";
var splts = Regex.Split(txt, @"([\W-[._$#\s]])|\s+").Where(s => s != String.Empty).ToArray(); 

输出:

enter image description here

正则表达式 - [\W-[._$#\s]])|\s+ - 使用character class subtraction,它比查看更有效,因为它利用了.NET正则表达式引擎的所有优化。 [\W-[._$#\s]]表示._$#whitespace 之外的任何非字词字符。< / p>

答案 1 :(得分:1)

(?!\.|#|_|\$|\s)(\W)|\s+

试试这个。lookahead会确保它不会被这些字符拆分。