Skip to main content

Find and Highlight Text in Word Documents Using Java

When reviewing Word documents, you may need to highlight specific words or phrases. For example, you might want to mark every occurrence of "risk" in a report, or highlight phrases such as "risk assessment" and "risk analysis".

Java can handle both exact text searches and pattern-based searches. This article shows how to highlight the first match or all matches using either strings or regular expressions.

Find and Highlight Text in Word Documents Using Java

1. Install a Word Document Processing Library

Add the following repository and dependency to your Maven project's pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.9.5</version>
    </dependency>
</dependencies>

For the examples below, prepare a Word document named input.docx with the following content:

We identified a potential risk before the release.

The audit covers risk assessment and risk-analysis.

A risk review is scheduled for next week.

Another Risk Assessment will happen after launch.

Each example works independently and saves the modified document to a separate file.

2. Highlight the First Occurrence of a Word

To highlight only the first occurrence of a word, use Document.findString(). This method returns a TextSelection representing the first match.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;

import java.awt.Color;

public class HighlightFirstOccurrence {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            // Load the Word document
            document.loadFromFile("input.docx");

            // Find the first occurrence of "risk"
            TextSelection selection =
                    document.findString("risk", false, false);

            // Highlight the matching text
            if (selection != null) {
                selection.getAsOneRange()
                        .getCharacterFormat()
                        .setHighlightColor(Color.YELLOW);
            }

            // Save the modified document
            document.saveToFile(
                    "HighlightFirst.docx",
                    FileFormat.Docx_2013);

        } finally {
            document.dispose();
        }
    }
}

The two Boolean arguments in findString() control case sensitivity and whole-word matching:

  • caseSensitive: When false, both "risk" and "Risk" can match.

  • wholeWord: When false, the search can also match text within longer words.

Here, both are set to false.

The code uses getAsOneRange() to access the matched text and setHighlightColor() to apply yellow highlighting.

For the sample document, only "risk" in the first sentence is highlighted. The null check prevents an error if no match is found.

3. Highlight All Occurrences of a Word

To highlight every occurrence of a word, use Document.findAllString() instead.

Unlike findString(), which returns a single match, this method returns a TextSelection[] array containing all matches.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;

import java.awt.Color;

public class HighlightAllOccurrences {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            // Load the Word document
            document.loadFromFile("input.docx");

            // Find all occurrences of "risk"
            TextSelection[] selections =
                    document.findAllString(
                            "risk", false, false);

            // Highlight all matching text
            if (selections != null) {
                for (TextSelection selection : selections) {
                    selection.getAsOneRange()
                            .getCharacterFormat()
                            .setHighlightColor(Color.YELLOW);
                }
            }

            // Save the modified document
            document.saveToFile(
                    "HighlightAll.docx",
                    FileFormat.Docx_2013);

        } finally {
            document.dispose();
        }
    }
}

The code loops through the returned selections and applies yellow highlighting to each one.

In the sample document, "risk" appears five times, including the capitalized "Risk". All five occurrences are highlighted because case-sensitive matching is disabled.

Only the matched text is highlighted, not the entire paragraph.

4. Highlight Text Using Regular Expressions

Exact string searches work when the target text is known. Regular expressions are useful when the text follows a pattern but may contain variations.

For example, a document may contain:

  • risk assessment

  • risk-analysis

  • risk review

  • Risk Assessment

These phrases can be matched using one regular expression:

Pattern pattern = Pattern.compile(
        "(?i)\\brisk[\\s-]+"
        + "(?:assessment|analysis|review)\\b");

The pattern uses:

  • (?i) for case-insensitive matching.

  • \\b for word boundaries.

  • [\\s-]+ for one or more whitespace characters or hyphens.

  • (?:assessment|analysis|review) for the allowed terms.

The backslashes are doubled because the pattern is written as a Java string.

4.1 Highlight the First Regex Match

Use Document.findPattern() to find the first text matching a regular expression.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;

import java.awt.Color;
import java.util.regex.Pattern;

public class HighlightFirstPattern {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            // Load the Word document
            document.loadFromFile("input.docx");

            // Define the regex pattern
            Pattern pattern = Pattern.compile(
                    "(?i)\\brisk[\\s-]+"
                    + "(?:assessment|analysis|review)\\b");

            // Find the first matching phrase
            TextSelection selection =
                    document.findPattern(pattern);

            // Highlight the matching phrase
            if (selection != null) {
                selection.getAsOneRange()
                        .getCharacterFormat()
                        .setHighlightColor(Color.YELLOW);
            }

            // Save the modified document
            document.saveToFile(
                    "HighlightFirstPattern.docx",
                    FileFormat.Docx_2013);

        } finally {
            document.dispose();
        }
    }
}

For the sample document, the first matching phrase is "risk assessment" in the second paragraph. Only this phrase is highlighted.

The findPattern() method accepts a java.util.regex.Pattern object and returns a TextSelection for the first match.

4.2 Highlight All Regex Matches

To highlight every phrase that matches the pattern, use Document.findAllPattern().

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;

import java.awt.Color;
import java.util.regex.Pattern;

public class HighlightAllPatterns {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            // Load the Word document
            document.loadFromFile("input.docx");

            // Define the regex pattern
            Pattern pattern = Pattern.compile(
                    "(?i)\\brisk[\\s-]+"
                    + "(?:assessment|analysis|review)\\b");

            // Find all matching phrases
            TextSelection[] selections =
                    document.findAllPattern(pattern);

            // Highlight every matching phrase
            if (selections != null) {
                for (TextSelection selection : selections) {
                    selection.getAsOneRange()
                            .getCharacterFormat()
                            .setHighlightColor(Color.YELLOW);
                }
            }

            // Save the modified document
            document.saveToFile(
                    "HighlightAllPatterns.docx",
                    FileFormat.Docx_2013);

        } finally {
            document.dispose();
        }
    }
}

The method returns a TextSelection[] array, allowing each match to be highlighted.

For the sample document, the expected matches are "risk assessment", "risk-analysis", "risk review", and "Risk Assessment" — four phrases in total.

The entire matching phrase is highlighted rather than just the word "risk".

You can also use alternation to search for unrelated terms. For example, risk|delay|failure matches any of the three words.

5. Things to Keep in Mind

Text formatting and document structure

Word documents may contain text split across multiple runs, paragraphs, or other elements. Regular expressions that span these boundaries may not behave as expected. Test complex documents separately, particularly when searching across differently formatted text.

Highlight colors

The examples use Color.YELLOW, but you can choose another color, such as Color.GREEN.

Highlighting changes the background behind the matched characters. It does not change their font color.

File paths and output

The examples use relative file paths, so input.docx must be accessible from the program's working directory. You can use an absolute path if needed.

Each example saves a new DOCX file, leaving the original unchanged.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...