使用正则表达式分隔单个单词



我有以下行将句子拆分为单词,并将其存储在基于空格的数组中:string[] s = Regex.Split(input, @"s+");

问题是在句子的末尾,它还提到了句号。例如:C# is cool.
代码将存储:

  1. C#
  2. is
  3. cool.

问题是:我如何才能不来月经?

您可以使用字符类[]添加点.或其他需要拆分的字符。

string[] s = Regex.Split(input, @"[s.]+");

参见Demo

您可以在正则表达式中添加点(以及其他需要的标点符号),如下所示:

string[] s = Regex.Split(input, @"(s|[.;,])+");
string[] s = Regex.Split(input, @"[^w#]+");

您可能需要添加更多字符来设置[^w#],因此它将根据您的要求为您工作。。。

使用非单词字符模式:W

string[] s = Regex.Split(input, @"W+");

考虑使用Regex.Matches作为您需求的替代方案。。。

string[] outputMessage = Regex.Matches(inputMessage, @"w+").Cast<Match>().Select(match => match.Value).ToArray();

祝你好运!

最新更新