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:

Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.
public void replaceWithCallback() throws Exception
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.writeln("Our new location in New York City is opening tomorrow. " +
                    "Hope to see all our NYC-based customers at the opening!");

    // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
    FindReplaceOptions options = new FindReplaceOptions();

    // Set a callback that tracks any replacements that the "Replace" method will make.
    TextFindAndReplacementLogger logger = new TextFindAndReplacementLogger();
    options.setReplacingCallback(logger);

    doc.getRange().replace(Pattern.compile("New York City|NYC"), "Washington", options);

    Assert.assertEquals("Our new location in (Old value:\"New York City\") Washington is opening tomorrow. " +
                    "Hope to see all our (Old value:\"NYC\") Washington-based customers at the opening!", doc.getText().trim());

    Assert.assertEquals("\"New York City\" converted to \"Washington\" 20 characters into a 21 node." +
                    "\"NYC\" converted to \"Washington\" 42 characters into a 21 node.", logger.getLog().trim());
}

/// <summary>
/// Maintains a log of every text replacement done by a find-and-replace operation
/// and notes the original matched text's value.
/// </summary>
private static class TextFindAndReplacementLogger implements IReplacingCallback {
    public int replacing(ReplacingArgs args) {
        mLog.append(MessageFormat.format("\"{0}\" converted to \"{1}\" {2} characters into a {3} node.", args.getMatch().group(0), args.getReplacement(), args.getMatchOffset(), args.getMatchNode().getNodeType()));

        args.setReplacement(MessageFormat.format("(Old value:\"{0}\") {1}", args.getMatch().group(0), args.getReplacement()));
        return ReplaceAction.REPLACE;
    }

    public String getLog() {
        return mLog.toString();
    }

    private StringBuilder mLog = new StringBuilder();
}

Example:

Shows how to insert an entire document's contents as a replacement of a match in a find-and-replace operation.
public void insertDocumentAtReplace() throws Exception
{
    Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");

    // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
    FindReplaceOptions options = new FindReplaceOptions();
    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 matched text.
        Paragraph para = (Paragraph)args.getMatchNode().getParentNode();
        insertDocument(para, subDoc);

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

        return ReplaceAction.SKIP;
    }
}

/// <summary>
/// Inserts all the nodes of another document after a paragraph or table.
/// </summary>
private static void insertDocument(Node insertionDestination, Document docToInsert)
{
    if (((insertionDestination.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE)))
    {
        CompositeNode dstStory = insertionDestination.getParentNode();

        NodeImporter importer =
                new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);

        for (Section srcSection : docToInsert.getSections())
            for (Node srcNode : srcSection.getBody())
            {
                // Skip the node if it is the last empty paragraph in a section.
                if (((srcNode.getNodeType()) == (NodeType.PARAGRAPH)))
                {
                    Paragraph para = (Paragraph)srcNode;
                    if (para.isEndOfSection() && !para.hasChildNodes())
                        continue;
                }

                // Clone the node, and insert it into the destination document.
                Node newNode = importer.importNode(srcNode, true);

                dstStory.insertAfter(newNode, insertionDestination);
                insertionDestination = newNode;
            }
    }
    else
    {
        throw new IllegalArgumentException("The destination node must 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 convertNumbersToHexadecimal() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.writeln("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\n" +
                            "123, 456, 789 and 17379.");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
        
            // Set the "HighlightColor" property to a background color that we want to apply to the operation's resulting text.
            options.getApplyFont().setHighlightColor(Color.GRAY);
        
            NumberHexer numberHexer = new NumberHexer();
            options.setReplacingCallback(numberHexer);
        
            int replacementCount = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            System.out.println(numberHexer.getLog());
        
            Assert.assertEquals(4, replacementCount);
            Assert.assertEquals("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\r" +
                            "0x123, 0x456, 0x789 and 0x17,379.", doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces numeric find-and-replacement matches with their hexadecimal equivalents
        /// and also logs every replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback
        {
            public int replacing(ReplacingArgs args)
            {
                mCurrentReplacementNumber++;
        
                int number = Integer.parseInt(args.getMatch().group(0));
        
                args.setReplacement(MessageFormat.format("0x{0}", number));
        
                mLog.append(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                mLog.append(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group(0)));
                mLog.append(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                mLog.append(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            public String getLog()
            {
                return mLog.toString();
            }
        
            private int mCurrentReplacementNumber;
            private StringBuilder mLog = new StringBuilder();
        }
      • 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 convertNumbersToHexadecimal() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.writeln("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\n" +
                            "123, 456, 789 and 17379.");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
        
            // Set the "HighlightColor" property to a background color that we want to apply to the operation's resulting text.
            options.getApplyFont().setHighlightColor(Color.GRAY);
        
            NumberHexer numberHexer = new NumberHexer();
            options.setReplacingCallback(numberHexer);
        
            int replacementCount = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            System.out.println(numberHexer.getLog());
        
            Assert.assertEquals(4, replacementCount);
            Assert.assertEquals("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\r" +
                            "0x123, 0x456, 0x789 and 0x17,379.", doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces numeric find-and-replacement matches with their hexadecimal equivalents
        /// and also logs every replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback
        {
            public int replacing(ReplacingArgs args)
            {
                mCurrentReplacementNumber++;
        
                int number = Integer.parseInt(args.getMatch().group(0));
        
                args.setReplacement(MessageFormat.format("0x{0}", number));
        
                mLog.append(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                mLog.append(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group(0)));
                mLog.append(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                mLog.append(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            public String getLog()
            {
                return mLog.toString();
            }
        
            private int mCurrentReplacementNumber;
            private StringBuilder mLog = new StringBuilder();
        }
      • getMatchNode

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

        Example:

        Shows how to insert an entire document's contents as a replacement of a match in a find-and-replace operation.
        public void insertDocumentAtReplace() throws Exception
        {
            Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
            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 matched text.
                Paragraph para = (Paragraph)args.getMatchNode().getParentNode();
                insertDocument(para, subDoc);
        
                // Remove the paragraph with the matched text.
                para.remove();
        
                return ReplaceAction.SKIP;
            }
        }
        
        /// <summary>
        /// Inserts all the nodes of another document after a paragraph or table.
        /// </summary>
        private static void insertDocument(Node insertionDestination, Document docToInsert)
        {
            if (((insertionDestination.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE)))
            {
                CompositeNode dstStory = insertionDestination.getParentNode();
        
                NodeImporter importer =
                        new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
                for (Section srcSection : docToInsert.getSections())
                    for (Node srcNode : srcSection.getBody())
                    {
                        // Skip the node if it is the last empty paragraph in a section.
                        if (((srcNode.getNodeType()) == (NodeType.PARAGRAPH)))
                        {
                            Paragraph para = (Paragraph)srcNode;
                            if (para.isEndOfSection() && !para.hasChildNodes())
                                continue;
                        }
        
                        // Clone the node, and insert it into the destination document.
                        Node newNode = importer.importNode(srcNode, true);
        
                        dstStory.insertAfter(newNode, insertionDestination);
                        insertionDestination = newNode;
                    }
            }
            else
            {
                throw new IllegalArgumentException("The destination node must 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 convertNumbersToHexadecimal() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.getFont().setName("Arial");
            builder.writeln("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\n" +
                            "123, 456, 789 and 17379.");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
        
            // Set the "HighlightColor" property to a background color that we want to apply to the operation's resulting text.
            options.getApplyFont().setHighlightColor(Color.GRAY);
        
            NumberHexer numberHexer = new NumberHexer();
            options.setReplacingCallback(numberHexer);
        
            int replacementCount = doc.getRange().replace(Pattern.compile("[0-9]+"), "", options);
        
            System.out.println(numberHexer.getLog());
        
            Assert.assertEquals(4, replacementCount);
            Assert.assertEquals("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\r" +
                            "0x123, 0x456, 0x789 and 0x17,379.", doc.getText().trim());
        }
        
        /// <summary>
        /// Replaces numeric find-and-replacement matches with their hexadecimal equivalents
        /// and also logs every replacement.
        /// </summary>
        private static class NumberHexer implements IReplacingCallback
        {
            public int replacing(ReplacingArgs args)
            {
                mCurrentReplacementNumber++;
        
                int number = Integer.parseInt(args.getMatch().group(0));
        
                args.setReplacement(MessageFormat.format("0x{0}", number));
        
                mLog.append(MessageFormat.format("Match #{0}", mCurrentReplacementNumber));
                mLog.append(MessageFormat.format("\tOriginal value:\t{0}", args.getMatch().group(0)));
                mLog.append(MessageFormat.format("\tReplacement:\t{0}", args.getReplacement()));
                mLog.append(MessageFormat.format("\tOffset in parent {0} node:\t{1}", args.getMatchNode().getNodeType(), args.getMatchOffset()));
        
                return ReplaceAction.REPLACE;
            }
        
            public String getLog()
            {
                return mLog.toString();
            }
        
            private int mCurrentReplacementNumber;
            private StringBuilder mLog = new StringBuilder();
        }
      • getReplacement/setReplacement

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

        Example:

        Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.
        public void replaceWithCallback() throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.writeln("Our new location in New York City is opening tomorrow. " +
                            "Hope to see all our NYC-based customers at the opening!");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
        
            // Set a callback that tracks any replacements that the "Replace" method will make.
            TextFindAndReplacementLogger logger = new TextFindAndReplacementLogger();
            options.setReplacingCallback(logger);
        
            doc.getRange().replace(Pattern.compile("New York City|NYC"), "Washington", options);
        
            Assert.assertEquals("Our new location in (Old value:\"New York City\") Washington is opening tomorrow. " +
                            "Hope to see all our (Old value:\"NYC\") Washington-based customers at the opening!", doc.getText().trim());
        
            Assert.assertEquals("\"New York City\" converted to \"Washington\" 20 characters into a 21 node." +
                            "\"NYC\" converted to \"Washington\" 42 characters into a 21 node.", logger.getLog().trim());
        }
        
        /// <summary>
        /// Maintains a log of every text replacement done by a find-and-replace operation
        /// and notes the original matched text's value.
        /// </summary>
        private static class TextFindAndReplacementLogger implements IReplacingCallback {
            public int replacing(ReplacingArgs args) {
                mLog.append(MessageFormat.format("\"{0}\" converted to \"{1}\" {2} characters into a {3} node.", args.getMatch().group(0), args.getReplacement(), args.getMatchOffset(), args.getMatchNode().getNodeType()));
        
                args.setReplacement(MessageFormat.format("(Old value:\"{0}\") {1}", args.getMatch().group(0), args.getReplacement()));
                return ReplaceAction.REPLACE;
            }
        
            public String getLog() {
                return mLog.toString();
            }
        
            private StringBuilder mLog = new StringBuilder();
        }