2012-05-06 50 views
2

我有一串由([ \\t{}():;.,،\"\n])分隔的字。如何将该字符串拆分为StringBuilder,同时删除与模式@"\d|\s|/|-"匹配的任何单词,并删除长度小于2个字符的所有单词。最后,我想把它存储回字符串。拆分字符串到字符串biulder删除所有字符匹配模式

Regex r = new Regex("([ \\t{}():;.,،\"\n])"); 

    String[] tokens = r.Split(sb.ToString()); 
    List<string> filter = new List<string>(); 
    for (int i = 0; i < tokens.Length; i++) 
    { 
     ........................ 
     { 
      ..................... 
     } 


    } 

    ................ 

    return builder.ToString(); 
+0

尝试从第二个正则表达式中创建一个RegEx实例,并在该循环中对所有对IsMatch的调用使用同一个实例。也许这会加快速度。 –

+0

是否可以用快速的Linq代码来完成? –

+0

你能提供一个示例输入字符串和期望的输出吗? –

回答

0

我想出了这个。除了我使用LINQ并避免使用StringBuidler之外,它与您的解决方案没有什么不同。你会接受吗?

using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

class Program { 
    static void Main(string[] args) { 
     string value = "one or:another{3}"; 
     Regex exclude = new Regex(@"\d|\s|/|-", RegexOptions.Compiled); 
     string final = string.Join(" ", 
      (from s in Regex.Split(value, "([ \\t{}():;.,،\"\n])") 
       where s.Length > 2 && !exclude.IsMatch(s) 
       select s.Replace("ه‌","ه")).ToArray()); 

     // to get the List<string> instead: 
     List<string> l = (from s in Regex.Split(value, "([ \\t{}():;.,،\"\n])") 
      where s.Length > 2 && !exclude.IsMatch(s) 
      select s.Replace("ه‌","ه")).ToList(); 
    } 
} 
+0

你的代码可以执行得更快吗?我应该试试。 –

+0

但我想存回字符串。 –

+0

那么,测试一下你的真实投入。我认为这只是避免一些不必要的步骤(StringBuilder位,列表),但我不认为它会快速发展。如果你的目标是速度,那么也许更低的水平会更好? –

0

该代码看起来不错。正则表达式处理确实需要很长时间。也许尝试创建@"\d\s|/|-"作为Regex m = new Regex( @“\ d \ s |/| - ”);`在顶部避免在每一圈重新分析它。

+0

对我来说不是专业,蚂蚁的建议提高? –

+0

理想情况下,这将作为基于集合的操作而不是循环来提​​高速度和效率 - O(1)而不是O(n)。也许尝试重新格式化为LINQ或将其移入存储过程 - 这两个都是基于集合的环境。 – robrich