com.aspose.words
Class FindReplaceOptions

java.lang.Object
    extended by com.aspose.words.FindReplaceOptions

public class FindReplaceOptions 
extends java.lang.Object

Specifies options for find/replace operations.

Example:

Simple find and replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test
System.out.println(doc.getFirstSection().getBody().getParagraphs().get(0).getText());

FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);

doc.getRange().replace("_CustomerName_", "James Bond", options);

doc.save(getArtifactsDir() + "Range.ReplaceSimple.docx");

Constructor Summary
FindReplaceOptions()
          
FindReplaceOptions(int direction)
          
FindReplaceOptions(IReplacingCallback replacingCallback)
          
FindReplaceOptions(int direction, IReplacingCallback replacingCallback)
          
 
Property Getters/Setters Summary
FontgetApplyFont()
           Text formatting applied to new content.
ParagraphFormatgetApplyParagraphFormat()
           Paragraph formatting applied to new content.
intgetDirection()
voidsetDirection(int value)
           Selects direction for replace. Default value is FindReplaceDirection.FORWARD. The value of the property is FindReplaceDirection integer constant.
booleangetFindWholeWordsOnly()
voidsetFindWholeWordsOnly(boolean value)
           True indicates the oldValue must be a standalone word.
booleangetIgnoreDeleted()
voidsetIgnoreDeleted(boolean value)
           Gets or sets a boolean value indicating either to ignore text inside delete revisions. The default value is false.
booleangetIgnoreFields()
voidsetIgnoreFields(boolean value)
           Gets or sets a boolean value indicating either to ignore text inside fields. The default value is false.
booleangetIgnoreInserted()
voidsetIgnoreInserted(boolean value)
           Gets or sets a boolean value indicating either to ignore text inside insert revisions. The default value is false.
booleangetMatchCase()
voidsetMatchCase(boolean value)
           True indicates case-sensitive comparison, false indicates case-insensitive comparison.
booleangetPreserveMetaCharacters()
voidsetPreserveMetaCharacters(boolean value)
          Deprecated. True indicates that meta-characters beginning with "&" are preserved. Default value is false.
IReplacingCallbackgetReplacingCallback()
voidsetReplacingCallback(IReplacingCallback value)
           The user-defined method which is called before every replace occurrence.
booleangetUseLegacyOrder()
voidsetUseLegacyOrder(boolean value)
           True indicates that a text search is performed sequentially from top to bottom considering the text boxes. Default value is false.
booleangetUseSubstitutions()
voidsetUseSubstitutions(boolean value)
           Gets or sets a boolean value indicating whether to recognize and use substitutions within replacement patterns. The default value is false.
 

Constructor Detail

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 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;
}

getApplyParagraphFormat

public ParagraphFormat getApplyParagraphFormat()
Paragraph formatting applied to new content.

Example:

Shows how to affect the format of paragraphs with successful replacements.
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.writeln("And this one will.");

FindReplaceOptions options = new FindReplaceOptions();
options.getApplyParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);

int count = doc.getRange().replace(".&p", "!&p", options);
Assert.assertEquals(count, 2);

doc.save(getArtifactsDir() + "Range.ApplyParagraphFormat.docx");

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 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;
}

getFindWholeWordsOnly/setFindWholeWordsOnly

public boolean getFindWholeWordsOnly() / public void setFindWholeWordsOnly(boolean value)
True indicates the oldValue must be a standalone word.

Example:

Simple find and replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test
System.out.println(doc.getFirstSection().getBody().getParagraphs().get(0).getText());

FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);

doc.getRange().replace("_CustomerName_", "James Bond", options);

doc.save(getArtifactsDir() + "Range.ReplaceSimple.docx");

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 ignore text inside delete revisions.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert non-revised text
builder.writeln("Deleted");
builder.write("Text");

// Remove first paragraph with tracking revisions
doc.startTrackRevisions("John Doe", new Date());
doc.getFirstSection().getBody().getFirstParagraph().remove();
doc.stopTrackRevisions();

FindReplaceOptions options = new FindReplaceOptions();

// Replace 'e' in document ignoring deleted text
options.setIgnoreDeleted(true);
doc.getRange().replace("e", "*", options);
Assert.assertEquals(doc.getText(), "Deleted\rT*xt\f");

// Replace 'e' in document NOT ignoring deleted text
options.setIgnoreDeleted(false);
doc.getRange().replace("e", "*", options);
Assert.assertEquals(doc.getText(), "D*l*t*d\rT*xt\f");

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);

// Insert field with text inside
builder.insertField("INCLUDETEXT", "Text in field");

FindReplaceOptions options = new FindReplaceOptions();

// Replace 'e' in document ignoring text inside field
options.setIgnoreFields(true);

doc.getRange().replace(Pattern.compile("e"), "*", options);
Assert.assertEquals(doc.getText(), "\u0013INCLUDETEXT\u0014Text in field\u0015\f");

// Replace 'e' in document NOT ignoring text inside field
options.setIgnoreFields(false);
doc.getRange().replace(Pattern.compile("e"), "*", options);
Assert.assertEquals(doc.getText(), "\u0013INCLUDETEXT\u0014T*xt in fi*ld\u0015\f");

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 ignore text inside insert revisions.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert text with tracking revisions
doc.startTrackRevisions("John Doe", new Date());
builder.writeln("Inserted");
doc.stopTrackRevisions();

// Insert non-revised text
builder.write("Text");

FindReplaceOptions options = new FindReplaceOptions();

// Replace 'e' in document ignoring inserted text
options.setIgnoreInserted(true);
doc.getRange().replace("e", "*", options);
Assert.assertEquals(doc.getText(), "Inserted\rT*xt\f");

// Replace 'e' in document NOT ignoring inserted text
options.setIgnoreInserted(false);
doc.getRange().replace("e", "*", options);
Assert.assertEquals(doc.getText(), "Ins*rt*d\rT*xt\f");

getMatchCase/setMatchCase

public boolean getMatchCase() / public void setMatchCase(boolean value)
True indicates case-sensitive comparison, false indicates case-insensitive comparison.

Example:

Simple find and replace operation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test
System.out.println(doc.getFirstSection().getBody().getParagraphs().get(0).getText());

FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);

doc.getRange().replace("_CustomerName_", "James Bond", options);

doc.save(getArtifactsDir() + "Range.ReplaceSimple.docx");

getPreserveMetaCharacters/setPreserveMetaCharacters

@Deprecated
public boolean getPreserveMetaCharacters() / public void setPreserveMetaCharacters(boolean value)
Deprecated. True indicates that meta-characters beginning with "&" are preserved. Default value is false.

getReplacingCallback/setReplacingCallback

public IReplacingCallback getReplacingCallback() / public void setReplacingCallback(IReplacingCallback value)
The user-defined method which is called before every replace occurrence.

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;
}

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 include text box analyzing, during replacing text.
public void useLegacyOrder(boolean isUseLegacyOrder) throws Exception {
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert 3 tags to appear in sequential order, the second of which will be inside a text box
    builder.writeln("[tag 1]");
    Shape textBox = builder.insertShape(ShapeType.TEXT_BOX, 100.0, 50.0);
    builder.writeln("[tag 3]");

    builder.moveTo(textBox.getFirstParagraph());
    builder.write("[tag 2]");

    UseLegacyOrderReplacingCallback callback = new UseLegacyOrderReplacingCallback();
    FindReplaceOptions options = new FindReplaceOptions();
    options.setReplacingCallback(callback);

    // Use this option if want to search text sequentially from top to bottom considering the text boxes
    options.setUseLegacyOrder(isUseLegacyOrder);

    Pattern pattern = Pattern.compile("\\[(.*?)\\]");
    doc.getRange().replace(pattern, "", options);

}

@DataProvider(name = "useLegacyOrderDataProvider")
public static Object[][] useLegacyOrderDataProvider() {
    return new Object[][]
            {
                    {true},
                    {false},
            };
}

private static class UseLegacyOrderReplacingCallback implements IReplacingCallback {
    public int replacing(ReplacingArgs e) {

        System.out.println(e.getMatch().group());
        return ReplaceAction.REPLACE;
    }

}

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 recognize and use substitutions within replacement patterns.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Write some text
builder.write("Jason give money to Paul.");

Pattern regex = Pattern.compile("([A-z]+) give money to ([A-z]+).");

// Replace text using substitutions
FindReplaceOptions options = new FindReplaceOptions();
options.setUseSubstitutions(true);
doc.getRange().replace(regex, "$2 take money from $1.", options);

Assert.assertEquals(doc.getText().trim(), "Paul take money from Jason.");

See Also:
          Aspose.Words Documentation - the home page for the Aspose.Words Product Documentation.
          Aspose.Words Support Forum - our preferred method of support.