Return Incorrect Match Node When Doing Search and Replace

Hi,
I want to search some specific text in document and then insert merge field at the position of match node. But unfortunately, I found that if there are several matchings, from the second match, the mode node is incorrect. The code I wrote is:

Document doc = new Document("ReplaceDoc.doc");
Regex regex = new Regex(@"ABC\d+", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, new TextFinder(), true);
class TextFinder: IReplacingCallback
{
    private DocumentBuilder builder = null;
    public ReplaceAction Replacing(ReplacingArgs args)
    {
        Node currentNode = args.MatchNode;
        if (builder == null)
            builder = new DocumentBuilder(currentNode.Document as Document);
        builder.MoveTo(currentNode);
        builder.InsertField(" MERGEFIELD ABC ");
        return ReplaceAction.Replace;
    }
}

I attached two documents here. One is template the other is output. It is obvious that in output the merge field is inserted at wrong position. Through debug, args.MatchNode is incorrect from second matching(3rd, 4th, and etc.) Could anybody investigate this issue?
thanks.

Hi Sheng,

Thanks for your inquiry. Please use the following code snippet to achieve your requirements. Hope this helps you. Please also check the code example shared at following forum link for your kind reference.
https://forum.aspose.com/t/55106

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

class TextFinder : IReplacingCallback
{
    public ArrayList nodes = new ArrayList();
    public ReplaceAction Replacing(ReplacingArgs args)
    {
        Node currentNode = args.MatchNode;
        nodes.Add(currentNode);
        args.Replacement = args.Replacement + "_Replace";
        return ReplaceAction.Replace;
    }
}
Document doc = new Document(MyDir + "ReplaceDoc.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
Regex regex = new Regex(@"ABC\d+", RegexOptions.IgnoreCase);
TextFinder tf = new TextFinder();
doc.Range.Replace(regex, tf, true);
foreach(Node node in tf.nodes)
{
    ((Run) node).Text = node.Range.Text.Replace("_Replace", "");
    Run run = new Run(doc, "");
    node.ParentNode.InsertAfter(run, node);
    builder.MoveTo(run);
    builder.InsertField("MERGEFIELD ABC");
}
doc.Save(MyDir + "out.docx");