Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/2eba8d1b1d2802076cd1252d49ebdf16 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/2eba8d1b1d2802076cd1252d49ebdf16 to your computer and use it in GitHub Desktop.
Find and Replace Text in Word using Java
// Load a Word DOCX document
Document doc = new Document("document.docx");
// Find and replace similar words in the document
FindReplaceOptions options = new FindReplaceOptions();
doc.getRange().replace(Pattern.compile("[B|S|M]ad"), "[replaced]", options);
// Save the Word document
doc.save("Find-And-Replace-Text.docx");
// Load a Word DOCX document
Document doc = new Document("document.docx");
// Find and replace text in the document
doc.getRange().replace("sad", "[replaced]", new FindReplaceOptions(FindReplaceDirection.FORWARD));
// Save the Word document
doc.save("Find-And-Replace-Text.docx");
// Load a Word DOCX document
Document doc = new Document("document.docx");
// Set options
FindReplaceOptions options = new FindReplaceOptions();
// Disable matching case and finding whole words only
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);
// Replace text with paragraph break
doc.getRange().replace("First paragraph ends.&pSecond paragraph starts.", "[replaced]", options);
// Save the Word document
doc.save("Find-And-Replace-Text.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment