DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Find and Replace Text by Regular Expressions in Word in Java applications

Spire.Doc for Java provides the ability to find the words that match a specific regular expression in a Word document. This article mainly introduce the feature of find and highlight/replace the text by regular expressions from the following two parts.

  • Find and replace the text by regular expressions in Word document
  • Find and highlight the text by regular expressions in Word document

Firstly, view the Sample document:
Sample Word
This demo shows how to use the document.replace() method offered by Spire.Doc to find all the text started with # and use Spire.Doc to replace them.

Java:

import com.spire.doc.*;
import java.util.regex.Pattern;

public class WordDemo {
    public static void main(String[] args) throws Exception {
        //Load the  sample document
        Document document = new Document();
        document.loadFromFile("Sample.docx");

        //Define a regular expression for the words that start with #.
        Pattern c = Pattern.compile ("^#(.*?)\\d$");
        //Use the new string “Spire.Doc” to replace all the searched texts.
        document.replace(c,"Spire.Doc");

        //Save the document to file
        document.saveToFile("Result.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Find and replace text in Word

This demo shows how to use the document.findAllPattern() method to search all the contents within【】even they are from the different paragraphs. And then highlight all the searched contents.

import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;

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

public class WordDemo {
    public static void main(String[] args) throws Exception {

        //Load the sample document
        Document document = new Document();
        document.loadFromFile("Sample.docx");

        Pattern c = Pattern.compile("【[\\s\\S]*】");
        //find all the contents within【】
        TextSelection[] textSelections = document.findAllPattern(c, true); 
       //Highlight the searched contents
        for (TextSelection selection : textSelections) {
            TextRange[] results = selection.getAsRange();
            for (TextRange result : results) {
                result.getCharacterFormat().setHighlightColor(Color.yellow);
            }
        }
        document.saveToFile("Result2.docx", FileFormat.Docx_2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Find and highlight text in Word

Top comments (0)