2012-08-23 72 views
0

生成在另一個字符串中找到的突出顯示的字符串的最佳方法是什麼?如何突出顯示忽略空格和非字母數字字符的字符串內的字符串?

我想忽略所有不是字母數字的字符,但將它們保留在最終輸出中。

因此,例如在以下3個字符串「PC3000」的搜索將給出以下結果:

ZxPc 3000L = Zx<font color='red'>Pc 3000</font>L 

    ZXP-C300-0Y = ZX<font color='red'>P-C300-0</font>Y 

    Pc3 000 = <font color='red'>Pc3 000</font> 

我有以下的代碼,但我可以突出顯示搜索中的結果是唯一的出路刪除所有空白字符和非字母數字字符,然後將這兩個字符串設置爲小寫字母。我卡住了!

public string Highlight(string Search_Str, string InputTxt) 
    { 

     // Setup the regular expression and add the Or operator. 
     Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase); 

     // Highlight keywords by calling the delegate each time a keyword is found. 
     string Lightup = RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords)); 

     if (Lightup == InputTxt) 
     { 
      Regex RegExp2 = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase); 
      RegExp2.Replace(" ", ""); 

      Lightup = RegExp2.Replace(InputTxt.Replace(" ", ""), new MatchEvaluator(ReplaceKeyWords)); 

      int Found = Lightup.IndexOf("<font color='red'>"); 

      if (Found == -1) 
      { 
       Lightup = InputTxt; 
      } 

     } 

     RegExp = null; 
     return Lightup; 
    } 

    public string ReplaceKeyWords(Match m) 
    { 
     return "<font color='red'>" + m.Value + "</font>"; 
    } 

謝謝你們!

+0

您能否提供一個輸入和輸出的例子?我假設基地是「剝離html標籤,然後找到字符串,即使它有空格」,我說得對嗎?另外,'突出顯示'你的意思是紅色? – Gabber

回答

0

通過將每個字符之間的可選的非字母數字字符類([^a-z0-9]?)改變搜索字符串。取而代之的PC3000使用

P[^a-z0-9]?C[^a-z0-9]?3[^a-z0-9]?0[^a-z0-9]?0[^a-z0-9]?0 

這符合Pc 3000P-C300-0Pc3 000

+0

我不知道該在哪裏做。所以我將字符串更改爲:string X =「」; foreach(InputTxt中的char c) {+} c.ToString()+「[^ a-z0-9]?」; } InputTxt = X; –

+0

你必須改變'Search_Str',而不是'InputTxt' – Stefan

+0

謝謝你謝謝! –

0

做到這一點的一種方法是創建一個只包含字母數字和一個查找數組的輸入字符串版本,該字符串將新字符串中的字符位置映射到原始輸入。然後搜索關鍵字的字母數字版本,並使用查找將匹配位置映射回原始輸入字符串。

用於構建查找陣列的僞代碼:

cleanInput = ""; 
lookup = []; 
lookupIndex = 0; 

for (index = 0; index < input.length; index++) { 
    if (isAlphaNumeric(input[index]) { 
     cleanInput += input[index]; 
     lookup[lookupIndex] = index; 
     lookupIndex++; 
    } 
} 
相關問題