DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How To Validate Archives and Identify Invalid Documents in Java
  • How To Get the Comments From a DOCX Document in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • How To Create and Edit PDF Annotations in Java

Trending

  • Vector Database: A Beginner's Guide
  • Generative AI Unleashed: MLOps and LLM Deployment Strategies for Software Engineers
  • Setting up Request Rate Limiting With NGINX Ingress
  • Breaking Down Silos: The Importance of Collaboration in Solution Architecture
  1. DZone
  2. Coding
  3. Java
  4. How to Find & Highlight a Specific Word or Phrase inside a Document using Java

How to Find & Highlight a Specific Word or Phrase inside a Document using Java

David Zondray user avatar by
David Zondray
·
Jan. 07, 15 · Code Snippet
Like (0)
Save
Tweet
Share
9.05K Views

Join the DZone community and get the full member experience.

Join For Free
This tutorial describes how java developers can programmatically find and highlight a particular word or a phrase inside a MS Word document using Aspose.Words. It might seem easy at first to just find the string of text in a document and change its formatting, but the main difficulty is that due to formatting, the match string could be spread over several runs of text. Consider the following example. The phrase “Hello World!” consists of three different runs, its beginning is italic, middle is bold, while the last part – regular text. In addition to formatting, any bookmarks in the middle of text will split it into more runs.   This article provides a solution designed to handle the described case – if necessary it collects the word (or phrase) from several runs, while skipping non-run nodes. The sample code will open a document and find any instance of the text “your document”. A replace handler is set up to handle the logic to be applied to each resulting match found. In this case the resulting runs are split around the txt and the resulting runs highlighted.
//Finds and highlights all instances of a particular word or a phrase in a Word document.

package FindAndHighlight;

import java.util.regex.Pattern;
import java.util.ArrayList;
import java.awt.Color;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.IReplacingCallback;
import com.aspose.words.ReplaceAction;
import com.aspose.words.NodeType;
import com.aspose.words.ReplacingArgs;
import com.aspose.words.Node;
import com.aspose.words.Run;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        Document doc = new Document(dataDir + "TestFile.doc");

        // We want the "your document" phrase to be highlighted.
        Pattern regex = Pattern.compile("your document", Pattern.CASE_INSENSITIVE);
        // Generally it is recommend if you are modifying the document in a custom replacement evaluator
        // then you should use backward replacement by specifying false value to the third parameter of the replace method.
        doc.getRange().replace(regex, new ReplaceEvaluatorFindAndHighlight(), false);

        // Save the output document.
        doc.save(dataDir + "TestFile Out.doc");
    }
}

class ReplaceEvaluatorFindAndHighlight implements IReplacingCallback
{
    /**
     * This method is called by the Aspose.Words find and replace engine for each match.
     * This method highlights the match string, even if it spans multiple runs.
     */
    public int replacing(ReplacingArgs e) throws Exception
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();

        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());

        // This array is used to store all nodes of the match for further highlighting.
        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
            (remainingLength > 0) &&
            (currentNode != null) &&
            (currentNode.getText().length() <= remainingLength))
        {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();

            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.getNextSibling();
            }
            while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            splitRun((Run)currentNode, remainingLength);
            runs.add(currentNode);
        }

        // Now highlight all runs in the sequence.
        for (Run run : (Iterable) runs)
            run.getFont().setHighlightColor(Color.YELLOW);

        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
    }

    /**
    * Splits text of the specified run into two runs.
    * Inserts the new run just after the specified run.
    */
    private static Run splitRun(Run run, int position) throws Exception
    {
        Run afterRun = (Run)run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}
Phrase (software) Document Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How To Validate Archives and Identify Invalid Documents in Java
  • How To Get the Comments From a DOCX Document in Java
  • How to Convert Excel and CSV Documents to HTML in Java
  • How To Create and Edit PDF Annotations in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: