DEV Community

Cover image for Find and Highlight Text in Word Documents Using Java
Dheeraj Malik
Dheeraj Malik

Posted on

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.

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>
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)