Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.