Issue while Replacing pattern in word document using IReplacingCallback

Hi Team,

I am trying to replace a certain pattern in the word document with a tag. The code is not working fine if there are multiple occurrences of the pattern on the same line. It only replaces the first one.

Code for reference :

public static void main(String[] args) throws Exception {
com.aspose.words.License license = new com.aspose.words.License();
        license.setLicense("/home/saurabharora/Downloads/Aspose.Total.Product.Family.lic");
Document document = new Document("/home/saurabharora/Downloads/intermediate-document.docx");
        FindReplaceOptions options = new FindReplaceOptions();
        options.setReplacingCallback(new LineItemReplaceEvaluator());

        Pattern pattern = Pattern.compile("\\$\\{(\\d+__[a-zA-Z]+)::([^\\}]+)\\}", Pattern.CASE_INSENSITIVE);

        document.getRange().replace(pattern,"", options);

        doc.save("/home/saurabharora/Downloads/final-document.docx");
}

package com.sirionlabs.clauselibrary.templateformatting.util;

import com.aspose.words.*;
import com.sirionlabs.ruleengine.core.dto.NotRuleCriteria;

import java.util.ArrayList;

public class LineItemReplaceEvaluator implements IReplacingCallback {

    public LineItemReplaceEvaluator() {
    }


    public int replacing(ReplacingArgs e) throws Exception {

        Node currentNode = e.getMatchNode();


        try {
            if (e.getMatchOffset() > 0) currentNode = splitRun((Run) currentNode, e.getMatchOffset());
        } catch (Exception ex) {
            return ReplaceAction.SKIP;
        }

        ArrayList runs = new ArrayList();

        int remainingLength = e.getMatch().group().length();
        while ((remainingLength > 0) && (currentNode != null) && (currentNode.getText().length() <= remainingLength)) {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();

            do {
                currentNode = currentNode.getNextSibling();
            } while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }


        Node afterNode = null;
        if ((currentNode != null) && (remainingLength > 0)) {
            afterNode = splitRun((Run) currentNode, remainingLength);
            runs.add(currentNode);
        }
        Document document = (Document) e.getMatchNode().getDocument();

        Node matchNode = e.getMatchNode();

        Font font = null;
        if (NodeType.RUN == matchNode.getNodeType()) {
            Run runNode = (Run) matchNode;
            font = runNode.getFont();
        }

        Node nodeToInsert = null;
        StructuredDocumentTag contentTag = null;

        String group1 = e.getMatch().group(1);
        String[] split = group1.split("__");
        String lineItemId = split[0];
        String lineItemColumn = split[1];
        String tagName = null;
        String value = e.getMatch().group(2);

        if (e.getMatch() != null && e.getMatchNode().getParentNode() != null && e.getMatchNode().getParentNode().getNodeType() == NodeType.PARAGRAPH && e.getMatchNode().getParentNode().getNextSibling() != null && e.getMatchNode().getParentNode().getNextSibling().getNodeType() == NodeType.PARAGRAPH && e.getMatchNode().getParentNode().getNextSibling().getText().trim().startsWith(tagName) && e.getMatchNode().getParentNode().getNextSibling().getText().trim().endsWith("}")) {
            Paragraph paragraphSibling = (Paragraph) (e.getMatchNode().getParentNode().getNextSibling());
            for (Object node : paragraphSibling.getChildNodes(NodeType.RUN, true)) {
                ((Run) node).setText("");
            }
        }

        contentTag = new StructuredDocumentTag(document, SdtType.PLAIN_TEXT, MarkupLevel.INLINE);
        contentTag.isShowingPlaceholderText(false);
        contentTag.removeAllChildren();

        Run run = new Run(document);
        //run.getFont().setHighlightColor(new Color(0, 191, 255));
        contentTag.setTag("LINEITEMCC::" + group1);
        contentTag.setTitle("");
        run.setText(value);
        run.getFont().setSize(font.getSize());
        run.getFont().setBold(font.getBold());
        run.getFont().setItalic(font.getItalic());
        run.getFont().setUnderline(font.getUnderline());
        run.getFont().setColor(font.getColor());
        run.getFont().setName(font.getName());
        contentTag.getChildNodes(NodeType.ANY, false).add(run);

        contentTag.setLockContents(false);
        nodeToInsert = contentTag;
        DocumentBuilder builder = new DocumentBuilder(document);

        for (int i = 0; i <= runs.size() - 1; i++) {
            ((Run) runs.get(i)).setText("");
            if (i == runs.size() - 1) {
                if (((Run) runs.get(i)).getNextSibling() == null) {
                    builder.moveTo((Run) runs.get(i));
                } else {
                    builder.moveTo(((Run) runs.get(i)).getNextSibling());
                }
                builder.insertNode(nodeToInsert);
            }
        }
        /*if(currentNode instanceof Run){
            currentNode = afterNode;
        }*/

        return ReplaceAction.SKIP;
    }

    private static Run splitRun(Run run, int position) throws Exception {
        Run afterRun = (Run) run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}

ReplaceIssue.zip (20.8 KB)

Please help.

@ashu_agrawal_sirionlabs_com Please specify FindReplaceDirection.BACKWARD:

FindReplaceOptions options = new FindReplaceOptions();
options.setDirection(FindReplaceDirection.BACKWARD);
options.setReplacingCallback(new LineItemReplaceEvaluator());