2012-10-17 57 views
0

我試圖找到具有特定關鍵字的文本的某個部分。我做到了,但我認爲可能有更好的方法來做到這一點。使用正則表達式和C返回部分文本#

這裏是我的代碼,

/// <summary> 
    /// Return String containing the search word 
    /// </summary> 
    /// <param name="strInput">Raw Input</param> 
    /// <param name="searchWord">Search Word</param> 
    /// <param name="minLength">Output Text Length</param> 
    /// <returns></returns> 
    public static String StringHavingSearchPattern(String strInput, String searchWord, Int32 minLength) 
    { 
     //considering the return string empty 
     String rtn = String.Empty; 
     // 
     if (String.IsNullOrEmpty(strInput)) 
     { 
      return rtn; 
     } 
     // consider the raw input as return; 
     //rtn = strInput; 
     int length = strInput.Length; 

     //if the rawinput length is greater||equal than/to the min length 
     if (length >= minLength) 
     { 
      int currentSearchIndex = -1; 
      searchWord = String.Format(@"{0}", searchWord); 
      //currentSearchIndex = strInput.IndexOf(searchWord,StringComparison.InvariantCultureIgnoreCase); 
      Match m = Regex.Match(strInput, searchWord, RegexOptions.Multiline | RegexOptions.IgnoreCase); 
      if (m.Success) 
      { 
       currentSearchIndex = m.Index; 
       if (currentSearchIndex >= 0) 
       { 
        if (currentSearchIndex > 9) 
        { 
         if ((length - currentSearchIndex - 1) >= minLength) 
         { 
          rtn = strInput.Substring((currentSearchIndex - 9), minLength); 
         } 
         else 
         { 
          rtn = strInput.Substring((currentSearchIndex - 9), length - currentSearchIndex - 1); 
         } 
        } 
        else 
        { 
         rtn = strInput.Substring(0, minLength); 
        } 
       } 
       else 
       { 
        rtn = strInput.Substring(0, minLength); 
       } 
      } 
     } 
     rtn = Regex.Replace(rtn, searchWord, String.Format("<span style='color:yellow;background-color:blue;'>{0}</span>", searchWord), RegexOptions.IgnoreCase | RegexOptions.Multiline); 

     //rtn = rtn.Replace(searchWord, String.Format("<span style='color:yellow;background-color:blue;'>{0}</span>", searchWord)); 
     return rtn; 
    } 

尋找你的那種建議,以改善它。

+0

爲什麼你需要'minLength' ... – Anirudha

+2

http://codereview.stackexchange.com/ –

+2

http://codereview.stackexchange.com/;) –

回答

1

你的直覺是對的;可以使用一個單一的,簡單的正則表達式來實現這一點:

Match m = Regex.Match(strInput, "(.{0," + minLength.ToString() + "}" + searchWord + ".*)", ... 

這將創建,例如用於searchWord「關鍵詞」和minLength 10,下面的正則表達式,

(.{0,10}keyword.*) 

這意味着,「最多可捕獲10個字符,然後是「關鍵字」和剩餘文本。「然後,你可以抓住的拍攝組:

m.Groups[1].Value 

注意,被覆蓋的搜索條件前,那裏有小於minLength字符的情況。

+0

非常感謝。我累了,但沒有給出正確的結果。從上面的表達式,它會是((。{,10} strInput。*),而不是(。{,10}關鍵字。*)? – Hoque

+0

糟糕,是的,我的意思是'searchWord''編輯解決方案。工作完成後,改變了嗎? –

+0

嘗試,很快就會回來。 – Hoque

相關問題