java.lang.Object
com.aspose.words.FindReplaceOptions
public class FindReplaceOptions
- extends java.lang.Object
Specifies options for find/replace operations.
Example:
Shows how to toggle case sensitivity when performing a find-and-replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Ruby bought a ruby necklace.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
// Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
options.setMatchCase(matchCase);
doc.getRange().replace("Ruby", "Jade", options);
Assert.assertEquals(matchCase ? "Jade bought a ruby necklace." : "Jade bought a Jade necklace.",
doc.getText().trim());
Example:
Shows how to toggle standalone word-only find-and-replace operations.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Jackson will meet you in Jacksonville.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "FindWholeWordsOnly" flag to "true" to replace the found text
// only as long as it is not a part of another word.
// Set the "FindWholeWordsOnly" flag to "false" to disregard the surrounding text of the text we are replacing.
options.setFindWholeWordsOnly(findWholeWordsOnly);
doc.getRange().replace("Jackson", "Louis", options);
Assert.assertEquals(
findWholeWordsOnly ? "Louis will meet you in Jacksonville." : "Louis will meet you in Louisville.",
doc.getText().trim());
FindReplaceOptions
public FindReplaceOptions()
-
FindReplaceOptions
public FindReplaceOptions(int direction)
- Parameters:
direction
- A FindReplaceDirection value.
FindReplaceOptions
public FindReplaceOptions(IReplacingCallback replacingCallback)
-
FindReplaceOptions
public FindReplaceOptions(int direction, IReplacingCallback replacingCallback)
- Parameters:
direction
- A FindReplaceDirection value.
Property Getters/Setters Detail |
getApplyFont | |
public Font getApplyFont()
|
-
Text formatting applied to new content.
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();
}
-
Paragraph formatting applied to new content.
Example:
Shows how to add formatting to paragraphs in which a find-and-replace operation has found matches.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Every paragraph that ends with a full stop like this one will be right aligned.");
builder.writeln("This one will not!");
builder.write("This one also will.");
ParagraphCollection paragraphs = doc.getFirstSection().getBody().getParagraphs();
Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(0).getParagraphFormat().getAlignment());
Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(1).getParagraphFormat().getAlignment());
Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(2).getParagraphFormat().getAlignment());
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "Alignment" property to "ParagraphAlignment.Right" to right-align every paragraph
// that contains a match that the find-and-replace operation finds.
options.getApplyParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
// Replace every full stop that's right before a paragraph break with an exclamation point.
int count = doc.getRange().replace(".&p", "!&p", options);
Assert.assertEquals(2, count);
Assert.assertEquals(ParagraphAlignment.RIGHT, paragraphs.get(0).getParagraphFormat().getAlignment());
Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(1).getParagraphFormat().getAlignment());
Assert.assertEquals(ParagraphAlignment.RIGHT, paragraphs.get(2).getParagraphFormat().getAlignment());
Assert.assertEquals("Every paragraph that ends with a full stop like this one will be right aligned!\r" +
"This one will not!\r" +
"This one also will!", doc.getText().trim());
getDirection/setDirection | |
public int getDirection() / public void setDirection(int value)
|
-
Selects direction for replace. Default value is FindReplaceDirection.FORWARD.
The value of the property is FindReplaceDirection integer constant.
Example:
Shows how to determine which direction a find-and-replace operation traverses the document in.
public void direction(int findReplaceDirection) throws Exception
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert three runs which we can search for using a regex pattern.
// Place one of those runs inside a text box.
builder.writeln("Match 1.");
builder.writeln("Match 2.");
builder.writeln("Match 3.");
builder.writeln("Match 4.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Assign a custom callback to the "ReplacingCallback" property.
TextReplacementRecorder callback = new TextReplacementRecorder();
options.setReplacingCallback(callback);
// Set the "Direction" property to "FindReplaceDirection.Backward" to get the find-and-replace
// operation to start from the end of the range, and traverse back to the beginning.
// Set the "Direction" property to "FindReplaceDirection.Backward" to get the find-and-replace
// operation to start from the beginning of the range, and traverse to the end.
options.setDirection(findReplaceDirection);
doc.getRange().replace(Pattern.compile("Match \\d*"), "Replacement", options);
Assert.assertEquals("Replacement.\r" +
"Replacement.\r" +
"Replacement.\r" +
"Replacement.", doc.getText().trim());
switch (findReplaceDirection)
{
case FindReplaceDirection.FORWARD:
Assert.assertEquals(new String[] { "Match 1", "Match 2", "Match 3", "Match 4" }, callback.getMatches().toArray());
break;
case FindReplaceDirection.BACKWARD:
Assert.assertEquals(new String[] { "Match 4", "Match 3", "Match 2", "Match 1" }, callback.getMatches().toArray());
break;
}
}
@DataProvider(name = "directionDataProvider")
public static Object[][] directionDataProvider() {
return new Object[][]
{
{FindReplaceDirection.BACKWARD},
{FindReplaceDirection.FORWARD},
};
}
/// <summary>
/// Records all matches that occur during a find-and-replace operation in the order that they take place.
/// </summary>
private static class TextReplacementRecorder implements IReplacingCallback
{
public int replacing(ReplacingArgs e)
{
mMatches.add(e.getMatch().group(0));
return ReplaceAction.REPLACE;
}
public ArrayList<String> getMatches() { return mMatches; }
private ArrayList<String> mMatches = new ArrayList<String>();
}
getFindWholeWordsOnly/setFindWholeWordsOnly | |
public boolean getFindWholeWordsOnly() / public void setFindWholeWordsOnly(boolean value)
|
-
True indicates the oldValue must be a standalone word.
Example:
Shows how to toggle standalone word-only find-and-replace operations.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Jackson will meet you in Jacksonville.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "FindWholeWordsOnly" flag to "true" to replace the found text
// only as long as it is not a part of another word.
// Set the "FindWholeWordsOnly" flag to "false" to disregard the surrounding text of the text we are replacing.
options.setFindWholeWordsOnly(findWholeWordsOnly);
doc.getRange().replace("Jackson", "Louis", options);
Assert.assertEquals(
findWholeWordsOnly ? "Louis will meet you in Jacksonville." : "Louis will meet you in Louisville.",
doc.getText().trim());
getIgnoreDeleted/setIgnoreDeleted | |
public boolean getIgnoreDeleted() / public void setIgnoreDeleted(boolean value)
|
-
Gets or sets a boolean value indicating either to ignore text inside delete revisions.
The default value is
false
.
Example:
Shows how to include or ignore text inside delete revisions during a find-and-replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
builder.writeln("Hello again!");
// Start tracking revisions and remove the second paragraph, which will create a delete revision.
// That paragraph will persist in the document until we accept the delete revision.
doc.startTrackRevisions("John Doe", new Date());
doc.getFirstSection().getBody().getParagraphs().get(1).remove();
doc.stopTrackRevisions();
Assert.assertTrue(doc.getFirstSection().getBody().getParagraphs().get(1).isDeleteRevision());
// We can use a "FindReplaceOptions" object to modify the find and replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "IgnoreDeleted" flag to "true" to get the find-and-replace
// operation to ignore paragraphs that are delete revisions.
// Set the "IgnoreDeleted" flag to "false" to get the find-and-replace
// operation to also search for text inside delete revisions.
options.setIgnoreDeleted(ignoreTextInsideDeleteRevisions);
doc.getRange().replace("Hello", "Greetings", options);
Assert.assertEquals(
ignoreTextInsideDeleteRevisions
? "Greetings world!\rHello again!"
: "Greetings world!\rGreetings again!", doc.getText().trim());
getIgnoreFields/setIgnoreFields | |
public boolean getIgnoreFields() / public void setIgnoreFields(boolean value)
|
-
Gets or sets a boolean value indicating either to ignore text inside fields.
The default value is
false
.
Example:
Shows how to ignore text inside fields.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
builder.insertField("QUOTE", "Hello again!");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "IgnoreFields" flag to "true" to get the find-and-replace
// operation to ignore text inside fields.
// Set the "IgnoreFields" flag to "false" to get the find-and-replace
// operation to also search for text inside fields.
options.setIgnoreFields(ignoreTextInsideFields);
doc.getRange().replace("Hello", "Greetings", options);
Assert.assertEquals(
ignoreTextInsideFields
? "Greetings world!\r\u0013QUOTE\u0014Hello again!"
: "Greetings world!\r\u0013QUOTE\u0014Greetings again!", doc.getText().trim());
getIgnoreInserted/setIgnoreInserted | |
public boolean getIgnoreInserted() / public void setIgnoreInserted(boolean value)
|
-
Gets or sets a boolean value indicating either to ignore text inside insert revisions.
The default value is
false
.
Example:
Shows how to include or ignore text inside insert revisions during a find-and-replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
// Start tracking revisions and insert a paragraph. That paragraph will be an insert revision.
doc.startTrackRevisions("John Doe", new Date());
builder.writeln("Hello again!");
doc.stopTrackRevisions();
Assert.assertTrue(doc.getFirstSection().getBody().getParagraphs().get(1).isInsertRevision());
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "IgnoreInserted" flag to "true" to get the find-and-replace
// operation to ignore paragraphs that are insert revisions.
// Set the "IgnoreInserted" flag to "false" to get the find-and-replace
// operation to also search for text inside insert revisions.
options.setIgnoreInserted(ignoreTextInsideInsertRevisions);
doc.getRange().replace("Hello", "Greetings", options);
Assert.assertEquals(
ignoreTextInsideInsertRevisions
? "Greetings world!\rHello again!"
: "Greetings world!\rGreetings again!", doc.getText().trim());
getLegacyMode/setLegacyMode | |
public boolean getLegacyMode() / public void setLegacyMode(boolean value)
|
-
Gets or sets a boolean value indicating that old find/replace algorithm is used.
Use this flag if you need exactly the same behavior as before advanced find/replace feature was introduced.
Note that old algorithm does not support advanced features such as replace with breaks, apply formatting and so on.
getMatchCase/setMatchCase | |
public boolean getMatchCase() / public void setMatchCase(boolean value)
|
-
True indicates case-sensitive comparison, false indicates case-insensitive comparison.
Example:
Shows how to toggle case sensitivity when performing a find-and-replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Ruby bought a ruby necklace.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
// Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
options.setMatchCase(matchCase);
doc.getRange().replace("Ruby", "Jade", options);
Assert.assertEquals(matchCase ? "Jade bought a ruby necklace." : "Jade bought a Jade necklace.",
doc.getText().trim());
-
The user-defined method which is called before every replace occurrence.
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 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();
}
getUseLegacyOrder/setUseLegacyOrder | |
public boolean getUseLegacyOrder() / public void setUseLegacyOrder(boolean value)
|
-
True indicates that a text search is performed sequentially from top to bottom considering the text boxes.
Default value is false.
Example:
Shows how to change the searching order of nodes when performing a find-and-replace text operation.
public void useLegacyOrder(boolean useLegacyOrder) throws Exception
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert three runs which we can search for using a regex pattern.
// Place one of those runs inside a text box.
builder.writeln("[tag 1]");
Shape textBox = builder.insertShape(ShapeType.TEXT_BOX, 100.0, 50.0);
builder.writeln("[tag 2]");
builder.moveTo(textBox.getFirstParagraph());
builder.write("[tag 3]");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Assign a custom callback to the "ReplacingCallback" property.
TextReplacementTracker callback = new TextReplacementTracker();
options.setReplacingCallback(callback);
// If we set the "UseLegacyOrder" property to "true", the
// find-and-replace operation will go through all the runs outside of a text box
// before going through the ones inside a text box.
// If we set the "UseLegacyOrder" property to "false", the
// find-and-replace operation will go over all the runs in a range in sequential order.
options.setUseLegacyOrder(useLegacyOrder);
doc.getRange().replace("\\[tag \\d*\\]", "", options);
}
@DataProvider(name = "useLegacyOrderDataProvider")
public static Object[][] useLegacyOrderDataProvider() {
return new Object[][]
{
{true},
{false},
};
}
/// <summary>
/// Records the order of all matches occuring during a find-and-replace operation.
/// </summary>
private static class TextReplacementTracker implements IReplacingCallback
{
public int replacing(ReplacingArgs e)
{
mMatches.add(e.getMatch().group(1));
return ReplaceAction.REPLACE;
}
public ArrayList<String> getMatches() { return mMatches; };
private ArrayList<String> mMatches;
}
getUseSubstitutions/setUseSubstitutions | |
public boolean getUseSubstitutions() / public void setUseSubstitutions(boolean value)
|
-
Gets or sets a boolean value indicating whether to recognize and use substitutions within replacement patterns.
The default value is
false
.
For the details on substitution elements please refer to:
https://docs.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions.
Example:
Shows how to replace the text with substitutions.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("John sold a car to Paul.");
builder.writeln("Jane sold a house to Joe.");
// We can use a "FindReplaceOptions" object to modify the find-and-replace process.
FindReplaceOptions options = new FindReplaceOptions();
// Set the "UseSubstitutions" property to "true" to get
// the find-and-replace operation to recognize substitution elements.
// Set the "UseSubstitutions" property to "false" to ignore substitution elements.
options.setUseSubstitutions(useSubstitutions);
doc.getRange().replace(Pattern.compile("([A-z]+) sold a ([A-z]+) to ([A-z]+)"), "$3 bought a $2 from $1", options);
Assert.assertEquals(
useSubstitutions
? "Paul bought a car from John.\rJoe bought a house from Jane."
: "$3 bought a $2 from $1.\r$3 bought a $2 from $1.", doc.getText().trim());
See Also:
Aspose.Words Documentation - the home page for the Aspose.Words Product Documentation.
Aspose.Words Support Forum - our preferred method of support.