We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Replace text with mergefield

I am looking to do a find/replace on a document, where I find examples of text, and replace it with a mergefield. I wasn’t able to figure out how to do this using the IReplaceCallback procedure. I see how to insert a field using a document builder, but don’t know how to make it happen programmatically.

I attached 2 docs: original.doc has the name of the company in many different places within the doc.
withField.doc shows what I want to end up with. I want to replace strings of text (in this case the company name) with a mergefield called “Company Name”.

Rereading this, I’m afraid I wasn’t clear. I basically want to do a “reverse merge”, i.e. look for text in a document and insert a field in place of that text.

Hi Brian,

Thanks for your inquiry.

You can achieve your requirement by implementing IReplacingCallback interface. Please use the same approach shared at following documentation link to find text and insert the mail merge field. See the highlighted code snippet below.

Hope this helps you. Please let us know if you have any more queries.

public void FindandReplace(Document doc, String regexString, String newText) throws Exception
    ReplaceEvaluatorTest obj = new ReplaceEvaluatorTest();
    obj.newText = newText;
    Pattern regex = Pattern.compile(regexString, Pattern.CASE_INSENSITIVE);
    doc.getRange().replace(regex, obj, false);
class ReplaceEvaluatorTest implements IReplacingCallback
    public String newText;
    public int replacing(ReplacingArgs e) throws Exception
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();
        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());
        // This array is used to store all nodes of the match.
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
                (remainingLength > 0) &&
                        (currentNode != null) &&
                        (currentNode.getText().length() <= remainingLength))
            remainingLength = remainingLength - currentNode.getText().length();
            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
                currentNode = currentNode.getNextSibling();
            while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
            splitRun((Run)currentNode, remainingLength);
        DocumentBuilder builder = new DocumentBuilder((Document)currentNode.getDocument());
        builder.insertField("MERGEFIELD " + newText + " \\* MERGEFORMAT");
        // Remove runs
        for (Run run : (Iterable) runs)
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
        * Splits text of the specified run into two runs.
        * Inserts the new run just after the specified run.
    private Run splitRun(Run run, int position) throws Exception
        Run afterRun = (Run)run.deepClone(true);
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;

Thank you very much. This helps a great deal.

Hi Brian,

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