2011-04-22 55 views
4

数字我发现这个代码来获得一个字符串的所有单词,查找所有单词,而不使用正则表达式

static string[] GetWords(string input) 
{ 
    MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b"); 

    var words = from m in matches.Cast<Match>() 
       where !string.IsNullOrEmpty(m.Value) 
       select TrimSuffix(m.Value); 

    return words.ToArray(); 
} 

static string TrimSuffix(string word) 
{ 
    int apostrapheLocation = word.IndexOf('\''); 
    if (apostrapheLocation != -1) 
    { 
     word = word.Substring(0, apostrapheLocation); 
    } 

    return word; 
} 
  1. 请介绍有关的代码。
  2. 我怎样才能不数字的话吗?
+5

英语纠错:你大概的意思:请描述一下代码的功能和/或它是如何工作的。 “描述”是不合语法的,过于模糊。 – 2011-04-22 11:43:37

+0

@Robin Green谢谢,我是英语新手。 – Shahin 2011-04-22 11:47:46

回答

2

MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b"); 

的代码使用正则表达式,将寻找任何话。 \ B表示单词的边界\ w是字母数字POSIX类得到的一切字母(带或不带图形重音),数字和下划线有时和只是包含在与alphaNum沿列表“。所以基本上这就是寻找单词的开始和结尾并选择它。

然后

var words = from m in matches.Cast<Match>() 
        where !string.IsNullOrEmpty(m.Value) 
        select TrimSuffix(m.Value); 

是LINQ语法,在那里你可以做你的代码中类似SQL的查询。该代码从正则表达式中获取每一个匹配,并检查该值是否为空并且无空格。它也是您可以添加图形验证的地方。

与此:

static string TrimSuffix(string word) 
    { 
     int apostrapheLocation = word.IndexOf('\''); 
     if (apostrapheLocation != -1) 
     { 
      word = word.Substring(0, apostrapheLocation); 
     } 

     return word; 
    } 

被去除谁拥有它,想起来那是一部分的话“之前

话它会得到只有

3

2?我怎样才能没有数字的话吗?

你有[A-Za-z]

更换\w使您的正则表达式变得@"\b[A-Za-z']*\b"

然后你就不得不考虑TrimSuffix()。 regEx允许使用撇号,但TrimSuffix()只会提取左侧部分。所以“它”会变成“它”。

+0

好吧,但有些错误,因为: 我写了8zfa + 2t^4/13hs-2 我认为这个正则表达式的结果应该是:zfa,t,hs – Shahin 2011-04-22 11:56:53

+1

shaahin,现在遇到\ b不包括的问题数字。也许只是放弃,只会寻找“[A-Za-z'] *” – 2011-04-22 12:01:24

相关问题