2012-08-23 47 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++; 
    } 
} 
相关问题