7 Smart Ways to Find and Replace Text in a Word Document Using Java
Tags: java, productivity, word
Published: 2021-07-23 12:07:30

---
title: 7 Smart Ways to Find and Replace Text in a Word Document Using Java
published: true
date: 2021-07-23 11:24:21 UTC
tags: java, productivity, word, 
canonical_url: https://www.syncfusion.com/blogs/post/find-and-replace-text-in-word-document-using-java.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/7-Smart-Ways-to-Find-and-Replace-Text-in-a-Word-Document-Using-Java-672x372.png
---

Our Syncfusion [Java Word Library](https://www.syncfusion.com/word-framework/java/word-library "Link to Java Word Library") (Essential DocIO) allows you to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. The find and replace feature in the Java Word Library allows you to find text and replace it with any desired text, image, hyperlink, paragraph, table, part of a document, or entire document. It also allows you to quickly search for text by matching case and whole words. You can find each occurrence one by one or highlight all instances at once in a document.

This feature saves your time and effort by allowing you to use the [Regex](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0 "Link to the Regex Class") class. This class will automatically locate and replace a pattern of text in a lengthy Word document.

You can save the results in Word (DOCX, WordML), HTML, and RTF formats.

In this blog, we are going to learn these seven smart ways to find and replace text using our Java Word Library:

- [Find and replace text with other text](#find-and-replace-text-in-a-word-document-with-other-text).
- [Find and replace text with an image](#find-and-replace-text-in-a-word-document-with-an-image).
- [Find and replace a pattern of text with a merge field](#find-and-replace-text-in-a-word-document-with-merge-field).
- [Find and replace text with a table](#find-and-replace-text-in-a-word-document-with-a-table).
- [Find and replace text with another document](#find-and-replace-text-in-a-word-document-with-another-document).
- [Find and replace text extending to several paragraphs](#find-and-replace-text-extending-to-several-paragraphs).
- [Find text in a document and highlight it](#find-and-format-text).

## Find and replace text in a Word document with other text

The Java Word Library allows you to find text in a Word document and replace all the occurrences of that text programmatically.

The following code example illustrates how to replace all occurrences of a misspelled word with the correctly spelled word. Use the  **setReplaceFirst** property to replace only the first occurrence of the text.

```java
// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("Template.docx"));
// Finds all occurrences of a misspelled word and replaces them with the properly spelled word.
document.replace("Cyles", "Cycles", true, true);
// Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
```

![Find a Misspelled Word and Replace it with the Properly Spelled Word](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Find-a-Misspelled-Word-and-Replace-it-with-a-Properly-Spelled-Word.png)<figcaption>Find a Misspelled Word and Replace it with the Properly Spelled Word</figcaption>

**Note:** For more information, refer to the [Find and Replace Text in a Java Word Document demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/findandreplacetext "Link to Find and Replace Text in a Java Word Document demo on GitHub").

## Find and replace text in a Word document with an image

You can easily find placeholder text in a Word document and replace it with any desired image programmatically using our Java Word Library.

The following code example illustrates how to achieve this programmatically.

```java
//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndReplaceImage_Template.docx"));
//Finds all the image placeholder text in the Word document.
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("^//(.*)")));
for (int i = 0; i < textSelections.length; i++) {
   // Replaces the image placeholder text with desired image.
   WParagraph paragraph = new WParagraph(document);
   WPicture picture = (WPicture) paragraph
   .appendPicture(new FileInputStream(getDataDir(textSelections[i].getSelectedText() + ".png")));
   TextSelection newSelection = new TextSelection(paragraph, 0, 1);
   TextBodyPart bodyPart = new TextBodyPart(document);
   bodyPart.getBodyItems().add(paragraph);
   document.replace(textSelections[i].getSelectedText(), bodyPart, true, true);
}
//Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
```

![Find Text and Replace it with a Desired Image](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Finding-Text-and-Replacing-it-with-Desired-Image.png)<figcaption>Find Text and Replace it with a Desired Image</figcaption>

**Note:** For more information, refer to the [Replace Text with Image in a Java Word Document demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/replacetextwithimage "Link to Replace Text with Image in a Java Word Document demo on GitHub").

## Find and replace a pattern of text with a merge field

The Java Word Library allows you to easily find and replace words that follow a particular pattern using the [Regex class](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex "Link to the Regex class").

The following code example illustrates how to create a mail merge template by replacing a pattern of text (enclosed within « and ») in a Word document with the required merge fields.

```java
// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("ReplaceWithMergeFileds_Template.docx"));
// Finds all the placeholder text enclosed within '«' and '»' in the Word document.
TextSelection[] textSelections = document.findAll(
Pattern.compile(MatchSupport.trimPattern("«([(?i)image(?-i)]*:*[a-zA-Z0-9]*:*[a-zA-Z0-9]+)»")));
String[] searchedPlaceholders = new String[textSelections.length];
for (int i = 0; i < textSelections.length; i++) 
{
   searchedPlaceholders[(int) i] = textSelections[(int) i].getSelectedText();
}
for (int i = 0; i < searchedPlaceholders.length; i++) 
{
   WParagraph paragraph = new WParagraph(document);
   // Replaces the placeholder text enclosed within '«' and '»' with the desired merge field.
   paragraph.appendField(StringSupport.trimEnd(StringSupport.trimStart(searchedPlaceholders[i], '«'), '»'),
   FieldType.FieldMergeField);
   TextSelection newSelection = new TextSelection(paragraph, 0, paragraph.getItems().getCount());
   TextBodyPart bodyPart = new TextBodyPart(document);
   bodyPart.getBodyItems().add(paragraph);
   document.replace(searchedPlaceholders[(int) i], bodyPart, true, true, true);
}
// Saves the resultant file in the given path.
document.save("Result.docx");
document.close();
```

![Find a Pattern of Text and Replace it with Merge Fields](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Find-a-Pattern-of-Text-and-Replace-it-with-Merge-Fields.png)<figcaption>Find a Pattern of Text and Replace it with Merge Fields</figcaption>

**Note:** For more information, refer to the [Replace Text with Merge Field in a Java Word Document demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/replacetextwithmergefield "Link to Replace Text with Merge Field in a Java Word Document demo on GitHub").

## Find and replace text in a Word document with a table

Also, you can find placeholder text in a Word document and replace it with a table using our Java Word Library.

Refer to the following code example.

```java
// Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("ReplaceTextWithTable.docx");
// Creates a new table.
WTable table = new WTable(document);
table.resetCells(1, 6);
table.get(0, 0).setWidth(52f);
table.get(0, 0).addParagraph().appendText("Supplier ID");
table.get(0, 1).setWidth(128f);
table.get(0, 1).addParagraph().appendText("Company Name");
table.get(0, 2).setWidth(70f);
table.get(0, 2).addParagraph().appendText("Contact Name");
table.get(0, 3).setWidth(92f);
table.get(0, 3).addParagraph().appendText("Address");
table.get(0, 4).setWidth(66.5f);
table.get(0, 4).addParagraph().appendText("City");
table.get(0, 5).setWidth(56f);
table.get(0, 5).addParagraph().appendText("Country");
// Imports data to the table.
importDataToTable(table);
// Applies the built-in table style (Medium Shading 1 Accent 1) to the table.
table.applyStyle(BuiltinTableStyle.MediumShading1Accent1);
TextBodyPart bodyPart = new TextBodyPart(document);
bodyPart.getBodyItems().add(table);
// Replaces the table placeholder text with a new table.
document.replace("[Suppliers table]", bodyPart, true, true, true);
// Saves the resultant file in the given path.
document.save("Result.docx");
```

![Find Text and Replace it with a Desired Table](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Find-Text-and-Replace-it-with-a-Desired-Table.png)<figcaption>Find Text and Replace it with a Desired Table</figcaption>

**Note:** For more information, refer to the [Replace Text with Table in a Java Word Document demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/replacetextwithtable "Link to Replace Text with Table in a Java Word Document demo on GitHub").

## Find and replace text in a Word document with another document

The Java Word Library also provides support to find and replace text with another word document programmatically.

The following code example illustrates how to merge or combine Word documents by replacing text with another document (the content of a subheading).

```java
//Opens the Word template document.
WordDocument document = new WordDocument(getDataDir("ReplaceTextWithDocument_Template.docx"),FormatType.Docx);
TextSelection[] textSelections = document.findAll(Pattern.compile(MatchSupport.trimPattern("\\[(.*)\\]")));
for(int i = 0;i< textSelections.length;i++)
{
   WordDocument subDocument = new WordDocument(getDataDir( StringSupport.trimEnd(StringSupport.trimStart(textSelections[i].getSelectedText(), '['), ']')+ ".docx"),FormatType.Docx);
   document.replace(textSelections[(int)i].getSelectedText(),subDocument,true,true);
   subDocument.close();
}
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
```

![Find Text and Replace it with Another Word Document](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Find-Text-and-Replace-it-with-Another-Word-Document.png)<figcaption>Find Text and Replace it with Another Word Document</figcaption>

**Note:** For more information, refer to the [Replace Text with Another Document Using Java Word Library demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/replacetextwithdocument "Link to Replace Text with Another Document Using Java Word Library demo on GitHub").

## Find and replace text extending to several paragraphs

The Java Word Library offers some more APIs to find and replace text that extends to several paragraphs in a Word document. The following methods will assist you in various cases:

- **findSingleLine** – Finds the first occurrence of the text that extends to several paragraphs in a document.
- **findNextSingleLine** – Finds the next occurrence of the text that extends to several paragraphs in a document.
- **replaceSingleLine** – Replaces all occurrences of text that extend to several paragraphs in a document.

The following code example illustrates how to replace text that extends to several paragraphs.

```java
//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndReplaceSeveralParagraphs_Template.docx"),FormatType.Docx);
WordDocument subDocument = new WordDocument(getDataDir("Source.docx"), FormatType.Docx);//Gets the content from another Word document to replace.
TextBodyPart replacePart = new TextBodyPart(subDocument);
for(Object bodyItem_tempObj : subDocument.getLastSection().getBody().getChildEntities())
{
   TextBodyItem bodyItem = (TextBodyItem)bodyItem_tempObj;
   replacePart.getBodyItems().add(bodyItem.clone());
}
String placeholderText = "Suppliers/Vendors of Northwind"+"Customers of Northwind"+"Employee details of Northwind traders"+"The product information"+"The inventory details"+"The shippers"+"Purchase Order transactions"+"Sales Order transaction"+"Inventory transactions"+"Invoices"+"[end replace]";
//Finds the text that extends to several paragraphs and replaces it with desired content.
document.replaceSingleLine(placeholderText,replacePart,false,false);
subDocument.close();
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
```

![Find Text that Extends to Several Paragraphs and Replace It](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Find-Text-that-Extends-to-Several-Paragraphs-and-Replace-It.png)<figcaption>Find Text that Extends to Several Paragraphs and Replace It</figcaption>

**Note:** For more information, refer to the [Find and Replace Text Extending to Several Paragraphs in a Java Word Document example](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/findandreplaceseveralparagraphs "Link to Find and Replace Text Extending to Several Paragraphs in a Java Word Document demo on GitHub").

## Find and format text in a Word document

With the Syncfusion Java Word Library, you can easily find text in a Word document and format or highlight it programmatically. Find the first occurrence of the text using the  **find**  method. Find the next occurrence of the text using the  **findNext**  method.

The following code example illustrates how to find all occurrences of a text and highlight them.

```java
//Opens the input Word document.
WordDocument document = new WordDocument(getDataDir("FindAndHighlightText_Template.docx"), FormatType.Docx);
//Finds all occurrence of the text in the Word document.
TextSelection[] textSelections = document.findAll("Adventure",true,true);
for(int i = 0;i<textSelections.length;i++)
{
  //Sets the highlight color for the searched text as Yellow.
  textSelections[(int)i].getAsOneRange().getCharacterFormat().setHighlightColor(ColorSupport.getYellow());
}
//Saves the Word document.
document.save("Result.docx");
//Closes the document.
document.close();
```

![Find and Highlight Text in Java Word Library](https://www.syncfusion.com/blogs/wp-content/uploads/2021/07/Finding-and-Highlighting-text-in-Java-Word-Library.png)<figcaption>Find and Highlight Text in Java Word Library</figcaption>

Similarly, you can automate the process of highlighting or underlining any misspelled words in a Word document without using Microsoft Word.

**Note:** For more information, refer to the [Find and Highlight Text in a Java Word Document demo](https://github.com/SyncfusionExamples/Java-Word-Find-and-Replace-Examples/tree/main/findandhighlighttext "Link to Find and Highlight Text in a Java Word Document demo on GitHub").

## Summary

Thanks for reading! In this blog, we have seen seven smart ways to find and replace text in a Word document using the Syncfusion [Java Word Library](https://www.syncfusion.com/word-framework/java/word-library "Link to Java Word Library") (Essential DocIO). Take a moment to peruse the [documentation](https://help.syncfusion.com/java-file-formats/word-library/working-with-find-and-replace "Link to Working with Find and Replace in Java Word Library documentation"), where you’ll find other options and features, all with accompanying code examples. Using the Word Library, you can create, edit, and merge Word documents, as well as convert them to [HTML](https://help.syncfusion.com/java-file-formats/word-library/html "Link to Word to HTML and HTML to Word Conversions"), [RTF](https://help.syncfusion.com/java-file-formats/word-library/rtf "Link to Word to RTF and RTF to Word Conversions"), and other formats. Try out the methods discussed in this blog post and leave your feedback in the comments section below!

If you are new to our Word Library, it is highly recommended that you follow our [Getting Started guide](https://help.syncfusion.com/java-file-formats/word-library/getting-started "Link to Getting Started with Word Library (DocIO) documentation").

Are you already a Syncfusion user? You can download the [product setup](https://www.syncfusion.com/account/downloads/studio/ "Link to license and download page of Essential Studio"). If you’re not yet a Syncfusion user, you can download a [30-day free trial](https://www.syncfusion.com/downloads/fileformats/confirm "Link to the free evaluation of the Syncfusion Essential Studio").

You can also contact us through our [support forums](https://www.syncfusion.com/forums "Link to the Syncfusion support forums"), [Direct-Trac](https://www.syncfusion.com/support/directtrac "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/word "Link to Syncfusion Feedback Portal"). We are happy to assist you!

## Related blogs

- [Find and Replace Text in a Word Document Using C#](https://dev.to/syncfusion/7-useful-ways-to-find-and-replace-text-in-a-word-document-using-c-4j0c "Link to Find and Replace Text in a Word Document Using C# blog")
- [Converting Word to PDF programmatically [C#]](https://www.syncfusion.com/blogs/post/converting-word-docs-to-pdfs.aspx "Link to Converting Word to PDF programmatically [C#] blog")
- [How to Apply Table Styles to Word Tables in C# and VB.NET](https://dev.to/syncfusion/how-to-apply-table-styles-to-word-tables-in-c-and-vb-net-2mgd "Link to How to Apply Table Styles to Word Tables in C# and VB.NET blog")
- [Create and Update Table of Contents in Word Documents in .NET Core [C#]](https://dev.to/syncfusion/create-and-update-table-of-contents-in-word-documents-in-net-core-c-4o0j "Link to Create and Update Table of Contents in Word Documents in .NET Core [C#] blog")