2013-05-14 13 views
-1

得到的话,空格和标点基本上我想通过所有句子重复,例如:正则表达式:如何从字符串

string sentence = "How was your day - Andrew, Jane?"; 
string[] separated = SeparateSentence(sentence); 

separated输出如下:

[1] =“如何”

[2] = “”

[3] = “是”

[4] = “”

[5] = “您的”

[6] = “”

[7] = “天”

[8] = “”

[9] = “ - ”

[10] = “”

[11] = “安德鲁”

[12] = “”

[13] = “”

[14] = “Jane” 的

[15] = “?”

截至目前我只能用"\w(?<!\d)[\w'-]*"来抢词,正则表达式。 根据输出示例,如何将句子分成更小的部分?

编辑:字符串没有任何操作:

  • 固体形式

  • 8日,第1,第2

+0

标点,如'安德鲁,'和'简',将是一个问题?如果你有一个字符串,如'7 pm'。你愿意把它分成“7”还是“下”还是根本不分割? – 2013-05-14 14:07:05

+0

这里不会出现“8th”,“7pm”,“2nd”等词语,所以这不是问题 – Alex 2013-05-14 14:08:51

+0

这是一个糟糕的假设,你应该为它做好准备。 – 2013-05-14 14:10:28

回答

2

检查了这一点:

 string pattern = @"^(\s+|\d+|\w+|[^\d\s\w])+$"; 
     string input = "How was your 7 day - Andrew, Jane?"; 

     List<string> words = new List<string>(); 

     Regex regex = new Regex(pattern); 

     if (regex.IsMatch(input)) 
     { 
      Match match = regex.Match(input); 

      foreach (Capture capture in match.Groups[1].Captures) 
       words.Add(capture.Value); 
     } 
+0

它的工作!谢谢。比我打算使用的“词法分析器”方法简单得多 – Alex 2013-05-14 14:29:46

+0

请注意,该解决方案将“7 pm”分成“7”和“pm” – 2013-05-14 14:30:45

1

我建议你实现一个简单的词法r(如果存在这种情况)将一次读取一个字符的句子并生成您正在查找的输出。虽然不是最简单的解决方案,但它具有可扩展的优点,以便您的用例如@AndreCalil所建议的那样变得更加复杂。

+0

我想我明白你在说什么。对我而言,这可能效果不错。如果这是最好的解决方案,我会实施这个解决方案;) – Alex 2013-05-14 14:21:18

1

为什么不这样呢?它是针对你的测试案例量身定制的,但如果你添加标点符号,这可能是你正在寻找的。

(\w+|[,-?]) 

编辑:嗯,从安德烈的响应偷东西,这就是我设想:

string pattern = @"(\w+|[,-?])"; 
string input = "How was your 7 day - Andrew, Jane?"; 

List<string> words = new List<string>(); 

Regex regex = new Regex(pattern); 

if (regex.IsMatch(input)) 
{ 
    MatchCollection matches = regex.Matches(input); 

    foreach (Match m in matches) 
     words.Add(m.Groups[1].Value); 
}