1.利用正则获取文字位置
1 TextRange t=new TextRange(MyRichTextBox.Document.ContentStart,MyRichTextBox.Document.ContentEnd); 2 var strR=new StringBuilder(); 3 for (int i = 0; i < strKeyWord.Length; i++)//strKeyword为要查找的关键字 4 { 5 strR.Append("["); 6 strR.Append(strKeyWord[i]); 7 strR.Append("]"); 8 } 9 Regex regex = new Regex(strR.ToString()); 10 var matchs = regex.Matches(t.Text);
2.解析正则表达式结果并标记文字
1 foreach (Match match1 in match) 2 { 3 TextRange tr = new TextRange(GetTextPointerAtOffset(MainRichTextBox,match1.Index), GetTextPointerAtOffset(MainRichTextBox,match1.Index+match1.Length)); 4 tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);//设置关键字颜色 5 tr.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);//设置关键字加粗 6 }
3.GetTextPointerAtOffset函数(本函数转自https://answer-id.com/51419225)
1 /// The rich text box. 2 /// The offset. 3 /// The TextPointer at the given character offset 4 public TextPointer GetTextPointerAtOffset( RichTextBox richTextBox, int offset) 5 { 6 var navigator = richTextBox.Document.ContentStart; 7 int cnt = 0; 8 9 while (navigator.CompareTo(richTextBox.Document.ContentEnd) < 0) 10 { 11 switch (navigator.GetPointerContext(LogicalDirection.Forward)) 12 { 13 case TextPointerContext.ElementStart: 14 break; 15 case TextPointerContext.ElementEnd: 16 if (navigator.GetAdjacentElement(LogicalDirection.Forward) is Paragraph) 17 cnt += 2; 18 break; 19 case TextPointerContext.EmbeddedElement: 20 //TODO: Find out what to do here? 21 cnt++; 22 break; 23 case TextPointerContext.Text: 24 int runLength = navigator.GetTextRunLength(LogicalDirection.Forward); 25 26 if (runLength > 0 && runLength + cnt < offset) 27 { 28 cnt += runLength; 29 navigator = navigator.GetPositionAtOffset(runLength); 30 if (cnt > offset) 31 break; 32 continue; 33 } 34 cnt++; 35 break; 36 } 37 38 if (cnt > offset) 39 break; 40 41 navigator = navigator.GetPositionAtOffset(1, LogicalDirection.Forward); 42 43 }//End while. 44 45 return navigator; 46 }