2011-04-22 44 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

相關問題