Find and Replace

Overview

getRange, which Document inherits from Node, returns a Range object that represents the portion of a document that is contained in the node. For a Document that is the whole document. A Range represents a contiguous area in a document, and its replace method replaces every occurrence of a character string with another. A common use is filling a placeholder in a template, which is what the example below does.


Prerequisites

RequirementDetail
Java8 or later
DependencyThe package from Installation
Importimport com.aspose.words.*;

Replace Text in a Document

Open the document, call replace on its range with the text to find and the text to put in its place, and save the document. replace returns the number of replacements as an int; it returned 2 for a placeholder that appears twice. The comparison is case-insensitive.

import com.aspose.words.*;

Document doc = new Document("contract.docx");
doc.getRange().replace("{{CLIENT_NAME}}", "Acme Corp");
doc.save("contract-filled.docx");

Tips and Best Practices

  • Use a placeholder that cannot appear in normal text, such as {{CLIENT_NAME}}, so that only the intended places change.
  • Save to a new file name, as the example does, to keep the original.
  • replace also has an overload that takes FindReplaceOptions, which specifies options for find/replace operations.

Common Issues

IssueCauseFix
The compiler reports cannot find symbol for Document.The com.aspose.words package is not imported.Add import com.aspose.words.*;.
The compiler reports an unreported exception.The Document constructors, Document.save and some other methods declare throws Exception.Declare it on the calling method or catch it.

FAQ

What does replace return?

The number of replacements, as an int.

Does it replace all occurrences?

Yes. It replaces all occurrences of the specified character string with the replacement string, and the comparison is case-insensitive.

Can I set options?

Yes, through the overload that takes a FindReplaceOptions object.


API Reference Summary

Class / MethodDescription
Node.getRange()Returns a Range object that represents the portion of a document that is contained in this node.
RangeRepresents a contiguous area in a document.
Range.replace(pattern, replacement)Replaces all occurrences of a specified character string pattern with a replacement string.
FindReplaceOptionsSpecifies options for find/replace operations.

Related Guides

See Also