Hi
Thanks for your interesting inquiry. I think that you can use ReplaceEvaluator to achieve this. Also you should split your runs and then highlight it. See the following code example.
public void TestHighlightText_283()
{
// open document
Document doc = new Document(@"283_mail_farley.niehues@neomind.com.br\in.doc");
// create regular expression
Regex regex = new Regex("test");
// search text
doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceAction_283), true);
// save processed document
doc.Save(@"283_mail_farley.niehues@neomind.com.br\out.doc");
}
ReplaceAction ReplaceAction_283(object sender, ReplaceEvaluatorArgs e)
{
// split text of the match node
string[] arr = (e.MatchNode as Run).Text.Split(new string[] { e.Match.Value }, StringSplitOptions.RemoveEmptyEntries);
// create empty array list
ArrayList list = new ArrayList();
// if match node begins with searched text
if ((e.MatchNode as Run).Text.StartsWith(e.Match.Value))
{
Run run = new Run(e.MatchNode.Document);
run.Font.HighlightColor = Color.Yellow; //highlight text
run.Text = e.Match.Value;
list.Add(run);
}
// add athr text
for (int i = 0; i < arr.Length; i++)
{
Run run = new Run(e.MatchNode.Document);
run.Text = arr[i];
list.Add(run);
if (((e.MatchNode as Run).Text.EndsWith((e.Match.Value)) && i == arr.Length - 1) || i < arr.Length - 1)
{
Run run1 = new Run(e.MatchNode.Document);
run1.Font.HighlightColor = Color.Yellow;
run1.Text = e.Match.Value;
list.Add(run1);
}
}
// add created runs into the document
foreach (Run run in list)
{
(e.MatchNode as Run).ParentParagraph.InsertBefore(run, e.MatchNode);
}
// remove old run
(e.MatchNode as Run).ParentParagraph.ChildNodes.Remove(e.MatchNode);
return ReplaceAction.Skip;
}
I hope that it will help you.
Best regards.