【问题标题】:Highlighting the multiple keywords突出显示多个关键字
【发布时间】:2017-10-04 17:30:58
【问题描述】:

我试图突出显示 gridview 中的多个关键字。我尝试使用 forloop,但它只突出显示数组中的第一项。

    protected string HighlightText(string searchWord, string inputText)
    {

        // string[] strArray = new string[] { "Hello", "Welcome" };
        string s = "d,s";
        // Split string on spaces.
        // ... This will separate all the words.
        string[] words = s.Split(',');

        for (int i = 0; i < words.Length; i++)
        {
            //Console.WriteLine(word);
            searchWord = words[i];
            Regex expression = new Regex(searchWord.Replace(" ", "|"), RegexOptions.IgnoreCase);
            return expression.Replace(inputText, new MatchEvaluator(ReplaceKeywords));
        }
        return string.Empty;
    }

提前谢谢。

这是我只得到关键字“d”被突出显示的输出我还需要突出显示关键字“s”......

【问题讨论】:

  • return 在循环内部在第一次迭代中终止其执行。

标签: c# asp.net highlight


【解决方案1】:

你能不能试试这样,而不是循环关键字 1 by 1

string inputText = "this is keyword1 for test and keyword4 also";

Regex keywords= new Regex("keyword1|keyword2|keyword3|keyword4");
kewyords = kewyords.Replace("|", "\b|\b"); //or use \b between keywords

foreach (Match match in keywords.Matches(inputText))
{
   //get match.Index & match.Length for selection and color it
}

【讨论】:

  • 谢谢。我得到了答案,我只是将我的逗号从关键字字符串更改为管道符号,然后它对我来说很好。感谢您的好主意,我从您的回答中得到了这个想法。
猜你喜欢
  • 2010-10-31
  • 2016-05-30
  • 2011-02-14
  • 1970-01-01
  • 2012-03-09
  • 2017-10-18
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多