com.aspose.words

Class ReplacingArgs

  • java.lang.Object
    • com.aspose.words.ReplacingArgs
public class ReplacingArgs 
extends java.lang.Object

Provides data for a custom replace operation.

Example:

Replaces text specified with regular expression with HTML.
public void replaceWithInsertHtml() throws Exception {
    // Open the document
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.setReplacingCallback(new ReplaceWithHtmlEvaluator(options));

    doc.getRange().replace(Pattern.compile(" <CustomerName>,"), "", options);

    // Save the modified document
    doc.save(getArtifactsDir() + "Range.ReplaceWithInsertHtml.docx");
}

private class ReplaceWithHtmlEvaluator implements IReplacingCallback {
    ReplaceWithHtmlEvaluator(final FindReplaceOptions options) {
        mOptions = options;
    }

    /**
     * NOTE: This is a simplistic method that will only work well when the match
     * starts at the beginning of a run.
     */
    public int replacing(final ReplacingArgs e) throws Exception {
        DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
        builder.moveTo(e.getMatchNode());

        // Replace '<CustomerName>' text with a red bold name
        builder.insertHtml("<b><font color='red'>James Bond, </font></b>");
        e.setReplacement("");

        return ReplaceAction.REPLACE;
    }

    private FindReplaceOptions mOptions;
}

Example:

Shows how to insert content of one document into another during a customized find and replace operation.
public void insertDocumentAtReplace() throws Exception {
    Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");

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

    mainDoc.getRange().replace("[MY_DOCUMENT]", "", options);
    mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
}

private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
    public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception {
        Document subDoc = new Document(getMyDir() + "Document.docx");

        // Insert a document after the paragraph, containing the match text
        Paragraph para = (Paragraph) args.getMatchNode().getParentNode();
        insertDocument(para, subDoc);

        // Remove the paragraph with the match text
        para.remove();

        return ReplaceAction.SKIP;
    }
}

/// <summary>
/// Inserts content of the external document after the specified node.
/// </summary>
static void insertDocument(Node insertionDestination, Document docToInsert) {
    // Make sure that the node is either a paragraph or table
    if (((insertionDestination.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE))) {
        // We will be inserting into the parent of the destination paragraph
        CompositeNode dstStory = insertionDestination.getParentNode();

        // This object will be translating styles and lists during the import
        NodeImporter importer =
                new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);

        // Loop through all block level nodes in the body of the section
        for (Section srcSection : docToInsert.getSections())
            for (Node srcNode : srcSection.getBody()) {
                // Let's skip the node if it is a last empty paragraph in a section
                if (((srcNode.getNodeType()) == (NodeType.PARAGRAPH))) {
                    Paragraph para = (Paragraph) srcNode;
                    if (para.isEndOfSection() && !para.hasChildNodes())
                        continue;
                }

                // This creates a clone of the node, suitable for insertion into the destination document
                Node newNode = importer.importNode(srcNode, true);

                // Insert new node after the reference node
                dstStory.insertAfter(newNode, insertionDestination);
                insertionDestination = newNode;
            }
    } else {
        throw new IllegalArgumentException("The destination node should be either a paragraph or table.");
    }
}
See Also:
IReplacingCallback, Range, Range.replace(java.lang.String,java.lang.String,com.aspose.words.FindReplaceOptions)

Property Getters/Setters Summary
intgetGroupIndex()
void
setGroupIndex(intvalue)
           Identifies, by index, a captured group in the Match that is to be replaced with the Replacement string.
java.util.regex.MatchergetMatch()
The java.util.regex.Matcher resulting from a single regular expression match during a Replace.
NodegetMatchNode()
Gets the node that contains the beginning of the match.
intgetMatchOffset()
Gets the zero-based starting position of the match from the start of the node that contains the beginning of the match.
java.lang.StringgetReplacement()
void
setReplacement(java.lang.Stringvalue)
           Gets or sets the replacement string.
 

    • Property Getters/Setters Detail

      • getGroupIndex/setGroupIndex

        public int getGroupIndex() / public void setGroupIndex(int value)
        
        Identifies, by index, a captured group in the Match that is to be replaced with the Replacement string.

        Default is zero.

        Example:

        Shows how to apply a different font to new content via FindReplaceOptions.
        public void replaceNumbersAsHex() throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.write("There are few numbers that should be converted to HEX and highlighted: 123, 456, 789 and 17379.");
        
            FindReplaceOptions options = new FindReplaceOptions();
            // Highlight newly inserted content with a color
            options.getApplyFont().setHighlightColor(new Color(255, 140, 0));
            // Apply an IReplacingCallback to make the replacement to convert integers into hex equivalents
            // and also to count replacements in the order they take place
            options.setReplacingCallback(new NumberHexer());
        
            // By default, text is searched for replacements front to back, but we can change it to go the other way
            options.setDirection(FindReplaceDirection.BACKWARD);
        
            int count = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            Assert.assertEquals(4, count);
            Assert.assertEquals("There are few numbers that should be converted to HEX and highlighted:" +
                            " 0x7b (replacement #4), 0x1c8 (replacement #3), 0x315 (replacement #2) and 0x43e3 (replacement #1).",
                    doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces arabic numbers with hexadecimal equivalents and appends the number of each replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback {
            public int replacing(ReplacingArgs args) {
                mCurrentReplacementNumber++;
        
                // Parse numbers
                String numberStr = args.getMatch().group();
                numberStr = numberStr.trim();
                // Java throws NumberFormatException both for overflow and bad format
                int number = Integer.parseInt(numberStr);
        
                // And write it as HEX
                args.setReplacement(MessageFormat.format("0x{0} (replacement #{1})", Integer.toHexString(number), mCurrentReplacementNumber));
        
                System.out.println(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                System.out.println(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group()));
                System.out.println(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                System.out.println(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            private int mCurrentReplacementNumber;
        }
      • getMatch

        public java.util.regex.Matcher getMatch()
        
        The java.util.regex.Matcher resulting from a single regular expression match during a Replace.

        Matcher.start() gets the zero-based starting position of the match from the start of the find and replace range.

        Example:

        Shows how to apply a different font to new content via FindReplaceOptions.
        public void replaceNumbersAsHex() throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.write("There are few numbers that should be converted to HEX and highlighted: 123, 456, 789 and 17379.");
        
            FindReplaceOptions options = new FindReplaceOptions();
            // Highlight newly inserted content with a color
            options.getApplyFont().setHighlightColor(new Color(255, 140, 0));
            // Apply an IReplacingCallback to make the replacement to convert integers into hex equivalents
            // and also to count replacements in the order they take place
            options.setReplacingCallback(new NumberHexer());
        
            // By default, text is searched for replacements front to back, but we can change it to go the other way
            options.setDirection(FindReplaceDirection.BACKWARD);
        
            int count = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            Assert.assertEquals(4, count);
            Assert.assertEquals("There are few numbers that should be converted to HEX and highlighted:" +
                            " 0x7b (replacement #4), 0x1c8 (replacement #3), 0x315 (replacement #2) and 0x43e3 (replacement #1).",
                    doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces arabic numbers with hexadecimal equivalents and appends the number of each replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback {
            public int replacing(ReplacingArgs args) {
                mCurrentReplacementNumber++;
        
                // Parse numbers
                String numberStr = args.getMatch().group();
                numberStr = numberStr.trim();
                // Java throws NumberFormatException both for overflow and bad format
                int number = Integer.parseInt(numberStr);
        
                // And write it as HEX
                args.setReplacement(MessageFormat.format("0x{0} (replacement #{1})", Integer.toHexString(number), mCurrentReplacementNumber));
        
                System.out.println(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                System.out.println(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group()));
                System.out.println(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                System.out.println(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            private int mCurrentReplacementNumber;
        }
      • getMatchNode

        public Node getMatchNode()
        
        Gets the node that contains the beginning of the match.

        Example:

        Shows how to insert content of one document into another during a customized find and replace operation.
        public void insertDocumentAtReplace() throws Exception {
            Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");
        
            FindReplaceOptions options = new FindReplaceOptions();
            options.setDirection(FindReplaceDirection.BACKWARD);
            options.setReplacingCallback(new InsertDocumentAtReplaceHandler());
        
            mainDoc.getRange().replace("[MY_DOCUMENT]", "", options);
            mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
        }
        
        private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
            public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception {
                Document subDoc = new Document(getMyDir() + "Document.docx");
        
                // Insert a document after the paragraph, containing the match text
                Paragraph para = (Paragraph) args.getMatchNode().getParentNode();
                insertDocument(para, subDoc);
        
                // Remove the paragraph with the match text
                para.remove();
        
                return ReplaceAction.SKIP;
            }
        }
        
        /// <summary>
        /// Inserts content of the external document after the specified node.
        /// </summary>
        static void insertDocument(Node insertionDestination, Document docToInsert) {
            // Make sure that the node is either a paragraph or table
            if (((insertionDestination.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE))) {
                // We will be inserting into the parent of the destination paragraph
                CompositeNode dstStory = insertionDestination.getParentNode();
        
                // This object will be translating styles and lists during the import
                NodeImporter importer =
                        new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
                // Loop through all block level nodes in the body of the section
                for (Section srcSection : docToInsert.getSections())
                    for (Node srcNode : srcSection.getBody()) {
                        // Let's skip the node if it is a last empty paragraph in a section
                        if (((srcNode.getNodeType()) == (NodeType.PARAGRAPH))) {
                            Paragraph para = (Paragraph) srcNode;
                            if (para.isEndOfSection() && !para.hasChildNodes())
                                continue;
                        }
        
                        // This creates a clone of the node, suitable for insertion into the destination document
                        Node newNode = importer.importNode(srcNode, true);
        
                        // Insert new node after the reference node
                        dstStory.insertAfter(newNode, insertionDestination);
                        insertionDestination = newNode;
                    }
            } else {
                throw new IllegalArgumentException("The destination node should be either a paragraph or table.");
            }
        }
      • getMatchOffset

        public int getMatchOffset()
        
        Gets the zero-based starting position of the match from the start of the node that contains the beginning of the match.

        Example:

        Shows how to apply a different font to new content via FindReplaceOptions.
        public void replaceNumbersAsHex() throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.write("There are few numbers that should be converted to HEX and highlighted: 123, 456, 789 and 17379.");
        
            FindReplaceOptions options = new FindReplaceOptions();
            // Highlight newly inserted content with a color
            options.getApplyFont().setHighlightColor(new Color(255, 140, 0));
            // Apply an IReplacingCallback to make the replacement to convert integers into hex equivalents
            // and also to count replacements in the order they take place
            options.setReplacingCallback(new NumberHexer());
        
            // By default, text is searched for replacements front to back, but we can change it to go the other way
            options.setDirection(FindReplaceDirection.BACKWARD);
        
            int count = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            Assert.assertEquals(4, count);
            Assert.assertEquals("There are few numbers that should be converted to HEX and highlighted:" +
                            " 0x7b (replacement #4), 0x1c8 (replacement #3), 0x315 (replacement #2) and 0x43e3 (replacement #1).",
                    doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces arabic numbers with hexadecimal equivalents and appends the number of each replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback {
            public int replacing(ReplacingArgs args) {
                mCurrentReplacementNumber++;
        
                // Parse numbers
                String numberStr = args.getMatch().group();
                numberStr = numberStr.trim();
                // Java throws NumberFormatException both for overflow and bad format
                int number = Integer.parseInt(numberStr);
        
                // And write it as HEX
                args.setReplacement(MessageFormat.format("0x{0} (replacement #{1})", Integer.toHexString(number), mCurrentReplacementNumber));
        
                System.out.println(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                System.out.println(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group()));
                System.out.println(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                System.out.println(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            private int mCurrentReplacementNumber;
        }
      • getReplacement/setReplacement

        public java.lang.String getReplacement() / public void setReplacement(java.lang.String value)
        
        Gets or sets the replacement string.

        Example:

        Replaces text specified with regular expression with HTML.
        public void replaceWithInsertHtml() throws Exception {
            // Open the document
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.writeln("Hello <CustomerName>,");
        
            FindReplaceOptions options = new FindReplaceOptions();
            options.setReplacingCallback(new ReplaceWithHtmlEvaluator(options));
        
            doc.getRange().replace(Pattern.compile(" <CustomerName>,"), "", options);
        
            // Save the modified document
            doc.save(getArtifactsDir() + "Range.ReplaceWithInsertHtml.docx");
        }
        
        private class ReplaceWithHtmlEvaluator implements IReplacingCallback {
            ReplaceWithHtmlEvaluator(final FindReplaceOptions options) {
                mOptions = options;
            }
        
            /**
             * NOTE: This is a simplistic method that will only work well when the match
             * starts at the beginning of a run.
             */
            public int replacing(final ReplacingArgs e) throws Exception {
                DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
                builder.moveTo(e.getMatchNode());
        
                // Replace '<CustomerName>' text with a red bold name
                builder.insertHtml("<b><font color='red'>James Bond, </font></b>");
                e.setReplacement("");
        
                return ReplaceAction.REPLACE;
            }
        
            private FindReplaceOptions mOptions;
        }