将句子分成单词,但在C#中标点符号有问题

我已经看到了一些类似的问题,但我正在努力实现这一目标。

给定一个字符串,str =“月亮是我们的天然卫星,即它围绕地球旋转!” 我想提取单词并将它们存储在一个数组中。 预期的数组元素就是这样。

the moon is our natural satellite ie it rotates around the earth 

我尝试使用String.split(’,’\ t’,’\ r’),但这不能正常工作。 我也尝试删除。和其他标点符号,但我想要一个像“ie”这样的字符串也要解析出来。 实现这一目标的最佳方法是什么? 我也尝试使用regex.split无济于事。

 string[] words = Regex.Split(line, @"\W+"); 

肯定会欣赏正确方向的一些推动。

正则表达式解决方案。

 (\b[^\s]+\b) 

如果你真的想要解决这个问题. 你可以使用这个。

 ((\b[^\s]+\b)((?<=\.\w).)?) 

这是我正在使用的代码。

  var input = "The moon is our natural satellite, ie it rotates around the Earth!"; var matches = Regex.Matches(input, @"((\b[^\s]+\b)((?<=\.\w).)?)"); foreach(var match in matches) { Console.WriteLine(match); } 

结果:

 The moon is our natural satellite ie it rotates around the Earth 

我怀疑你正在寻找的解决方案比你想象的要复杂得多。 您正在寻找某种forms的实际语言分析,或者至少是字典,以便您可以确定句点是单词的一部分还是结束句子。 你有没有考虑过它可以同时做到这两个事实?

考虑添加允许的“包含标点符号的单词”的字典。 这可能是解决问题的最简单方法。

这对我有用。

 var str="The moon is our natural satellite, ie it rotates around the Earth!"; var a = str.Split(new char[] {' ', '\t'}); for (int i=0; i < a.Length; i++) { Console.WriteLine(" -{0}", a[i]); } 

结果:

  -The -moon -is -our -natural -satellite, -ie -it -rotates -around -the -Earth! 

你可以对结果进行一些后处理,删除逗号和分号等。

 Regex.Matches(input, @"\b\w+\b").OfType().Select(m => m.Value)