public class ReplacingArgs
Example: Example:
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 final StringBuilder mLog = new StringBuilder();
}
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(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options);
mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
public int 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;
}
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.");
}
}
Property Getters/Setters Summary | ||
---|---|---|
int | getGroupIndex() | |
void | setGroupIndex(intvalue) | |
Identifies, by index, a captured group in the |
||
java.util.regex.Matcher | getMatch() | |
The |
||
Node | getMatchNode() | |
Gets the node that contains the beginning of the match.
|
||
int | getMatchOffset() | |
Gets the zero-based starting position of the match from the start of
the node that contains the beginning of the match.
|
||
java.lang.String | getReplacement() | |
void | setReplacement(java.lang.Stringvalue) | |
Gets or sets the replacement string. |
public int getGroupIndex() / public void setGroupIndex(int value)
Default is zero.
Example:
Shows how to apply a different font to new content via FindReplaceOptions.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. /// Maintains a log of 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 final StringBuilder mLog = new StringBuilder(); }
public java.util.regex.Matcher getMatch()
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.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. /// Maintains a log of 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 final StringBuilder mLog = new StringBuilder(); }
public Node getMatchNode()
Example:
Shows how to insert an entire document's contents as a replacement of a match in a find-and-replace operation.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(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options); mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx"); private static class InsertDocumentAtReplaceHandler implements IReplacingCallback { public int 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; } 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."); } }
public int getMatchOffset()
Example:
Shows how to apply a different font to new content via FindReplaceOptions.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. /// Maintains a log of 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 final StringBuilder mLog = new StringBuilder(); }
public java.lang.String getReplacement() / public void setReplacement(java.lang.String value)
Example:
Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.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 final StringBuilder mLog = new StringBuilder(); }