Highlight all searched words

后端 未结 6 732
耶瑟儿~
耶瑟儿~ 2020-12-16 00:35

In my RichtextBox, if I have written as below.

This is my pen,
his pen is beautiful.

Now I search word \"is\"

6条回答
  •  失恋的感觉
    2020-12-16 01:09

    If you only want to match the whole word you can use this, note that this ignores case and also the |s\b means that plurals get highlighted e.g. Cat matches cats but not caterpiller :

        public static void HighlightText(RichTextBox myRtb, string word, Color color)
        {
            if (word == string.Empty)
                return;
            var reg = new Regex(@"\b" + word + @"(\b|s\b)",RegexOptions.IgnoreCase);
    
            foreach (Match match in reg.Matches(myRtb.Text))
            {
                myRtb.Select(match.Index, match.Length);
                myRtb.SelectionColor = color;
            }
    
            myRtb.SelectionLength = 0;
            myRtb.SelectionColor = Color.Black;
        }
    

提交回复
热议问题