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:
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);
}
}
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);
}
}
Top comments (0)