搜索RegEx以将文本拆分为单词

我正在寻找一个RegularExpression来分割文字。 我测试过了

Regex.Split(text, @"\s+") 

但这给了我一些例子

 this (is a) text. and this (is a) text and 

但是我寻找一个解决方案,它只给出了单词 – 没有(,),. 它也应该拆分文本

 end.begin 

用两个字说。

你可能最好匹配单词而不是分裂。

如果您使用Split (使用\W作为Regexident建议 ),那么您可以在开头和结尾获得额外的字符串。 例如,输入字符串(ab)将为您提供四个输出: """a""b"和另一个"" ,因为您使用()作为分隔符。

你可能想要做的就是匹配单词。 你可以这样做:

 Regex.Matches(text, "\\w+").Cast().Select(match => match.Value) 

然后你将得到单词,并且在开头和结尾没有额外的空字符串。

试试这个:

 Regex.Split(text, @"\W+") 

\W\w的对应部分,表示字母数字。

你可以做:

 var text = "this (is a) text. and"; // to replace unwanted characters with space text = System.Text.RegularExpressions.Regex.Replace(text, "[(),.]", " "); // to split the text with SPACE delimiter var splitted = text.Split(null as char[], StringSplitOptions.RemoveEmptyEntries); foreach (var token in splitted) { Console.WriteLine(token); } 

看这个Demo