When reviewing a long document, it is often necessary to locate every paragraph that discusses a given topic and then check them one by one. The built-in Find feature in Word can locate only one occurrence at a time, which makes omissions likely in a document where headings, tables, and summary boxes are interleaved; marking each occurrence by hand also slows the review considerably.
Spire.Doc for C++ provides three search methods: Document->FindAllString(), Document->FindAllPattern(), and Document->FindString(). Every hit is returned as a TextSelection object. Applying character formatting to the returned text ranges highlights the matched text; the matched text, range count, and parent paragraph can also be read to produce a review checklist. All processing takes place in the local process, so the document does not need to be uploaded to any service.
This article covers three features:
- Find and highlight all matches
- Find text with a regular expression
- Find a single match and read the match information
The examples use the "2026 Third Quarter Quality Review Minutes" (QualityReview.docx). The second-level heading, body paragraphs, summary box, and risk register table all contain "risk", for a total of 14 occurrences. The document also contains 10 ISO dates, such as 2026-10-18 and 2026-11-30, and 3 occurrences of "deliverable", the first of which is located at body object index 9.

Install Spire.Doc for C++
There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.
- In Visual Studio, open the NuGet Package Manager, search for
Spire.Doc.Cpp, and install it. - Alternatively, run
nuget install Spire.Doc.Cppin the project directory, and then add the package'sincludeandlibfolders to the project.
An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.
Find and Highlight All Matches
Document->FindAllString() searches the entire document for the specified text and returns every hit as std::vector<intrusive_ptr<TextSelection>>. A TextSelection may cover one or more TextRange objects; iterate over GetRanges() and call GetCharacterFormat()->SetHighlightColor() on each range to highlight the matched text.
| Parameter | Meaning |
|---|---|
matchString |
The text to find |
caseSensitive |
Whether matching is case-sensitive |
wholeWord |
Whether to match only whole words |
The detailed steps are as follows.
- Create a Document object.
- Load the sample Word file with the Document->LoadFromFile() method.
- Call Document->FindAllString() to find the keyword and obtain all
TextSelectionresults. - Iterate over the
TextRangeobjects in each result and call CharacterFormat->SetHighlightColor() to apply highlighting. - Save the result document with the Document->SaveToFile() method.
The code for finding and highlighting all matches is shown below. The examples in the following two sections reuse the same set of header files and namespace references.
#include <iostream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
int main() {
// Specify the input file path
string inputFile = "QualityReview.docx";
// Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "FindAndHighlight.docx";
// Create a Document object
intrusive_ptr<Document> document = new Document();
// Load the Word file
document->LoadFromFile(inputFile.c_str());
// Find all occurrences of "risk" and return a collection of TextSelection
vector<intrusive_ptr<TextSelection>> selections =
document->FindAllString("risk", false, false);
// Iterate over the text ranges in each match and apply yellow highlighting
for (intrusive_ptr<TextSelection> selection : selections)
{
for (intrusive_ptr<TextRange> range : selection->GetRanges())
{
range->GetCharacterFormat()->SetHighlightColor(Color::GetYellow());
}
}
// Save the document as docx
document->SaveToFile(outputFile.c_str(), FileFormat::Docx);
document->Close();
}
After execution, all 14 occurrences of "risk" in the heading, body paragraphs, summary box, and table are displayed in yellow:

Parameters and Matching Rules
The last two parameters of FindAllString() control case sensitivity and whole-word matching. The sample passes false, false, so matching ignores case and also matches a fragment inside a longer word. English text is case-sensitive, and both parameters affect the result here: the 14 hits include both "Risk" and "risk". When searching for an English term and matching only complete words, set the third parameter to true.
The Search Scope Covers Body Text, Headings, Tables, and Headers and Footers
FindAllString() uses the entire document as its scope. Body paragraphs, headings at all levels, table cells, summary boxes built from tables, and headers and footers all fall within the search. The 14 hits in the sample comprise 1 second-level heading, 6 table entries, 1 summary-box phrase, and 6 body paragraphs, which shows that the hit count cannot be estimated from body paragraphs alone. Headers and footers are matched as well; in the sample they contain no keyword, so they are not counted among the 14 hits.
Find Text with a Regular Expression
A regular-expression search applies when the target is not a fixed literal. When the target is a class of text that shares a common format, combine Document->FindAllPattern() with a Regex object. The sample uses ISO dates as its target, matches strings of the form 2026-10-18, and then applies turquoise highlighting to all of them.
| Scenario | Regular expression |
|---|---|
| ISO date | \d{4}-\d{2}-\d{2} |
| Bracket placeholder | \[[A-Z_]+\] |
| Percentage | \d+(\.\d+)?% |
The detailed steps are as follows.
- Create a Document object and load the sample Word file.
- Include
Spire/Doc/common/h/Regex.hand construct aRegexobject with the regular expression. - Call Document->FindAllPattern() to obtain all matches.
- Iterate over the matched ranges and call CharacterFormat->SetHighlightColor() to apply a highlight color.
- Save the result document with the Document->SaveToFile() method.
The code for finding text with a regular expression is shown below.
#include <iostream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Regex.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
int main() {
// Specify the input file path
string inputFile = "QualityReview.docx";
// Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "RegexDates.docx";
// Create a Document object and load the document
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFile.c_str());
// Match ISO dates with a regular expression; note that a backslash is written twice in a string literal
intrusive_ptr<Regex> regex = new Regex("\\d{4}-\\d{2}-\\d{2}");
vector<intrusive_ptr<TextSelection>> selections =
document->FindAllPattern(regex);
// Apply turquoise highlighting to all matches
for (intrusive_ptr<TextSelection> selection : selections)
{
for (intrusive_ptr<TextRange> range : selection->GetRanges())
{
range->GetCharacterFormat()->SetHighlightColor(Color::GetTurquoise());
}
}
// Save the document as docx
document->SaveToFile(outputFile.c_str(), FileFormat::Docx);
document->Close();
}
The sample document contains 10 ISO dates distributed across the title area, body text, tables, and the signature line. After execution, these dates are all displayed in turquoise:

Backslashes in Regular Expressions Must Be Escaped
Metacharacters such as \d and \w contain a backslash, which is itself an escape character in a C++ string literal, so they must be written as \\d and \\w. The "\\d{4}-\\d{2}-\\d{2}" in the sample reaches Regex as \d{4}-\d{2}-\d{2}. Square brackets are part of regular-expression syntax, so matching a literal bracket requires \\[ and \\].
Regular-Expression Matches Are Also TextSelection
FindAllPattern() returns the same structure as FindAllString(): each item is a TextSelection, and GetRanges() can still be called to obtain the text ranges. Processing after the search therefore does not depend on how the matches were produced: highlighting, reading text, and grouping by paragraph all use the same set of methods.
Find a Single Match and Read the Match Information
When the goal is only to confirm whether a word exists in the document, or to obtain the position of the first match, use Document->FindString(). The method returns the first hit as a TextSelection and does not return the remaining results; the object can be used to read the matched text, the range count, and the parent paragraph.
| Item | How to read it |
|---|---|
| Matched text | selection->GetSelectedText() |
| Range count | selection->GetCount() |
| Single range | selection->GetAsOneRange() |
| All ranges | selection->GetRanges() |
| Parent paragraph | range->GetOwnerParagraph() |
| Paragraph text | paragraph->GetText() |
| Body object index | body->GetChildObjects()->IndexOf(paragraph) |
The detailed steps are as follows.
- Create a Document object and load the sample Word file.
- Call Document->FindString() to find the keyword and obtain the first match.
- Call TextSelection->GetAsOneRange() to obtain the text range.
- Obtain the parent paragraph and the body object through TextRange->GetOwnerParagraph() and Paragraph->GetOwnerTextBody().
- Read the matched text, range count, and paragraph index, and apply red highlighting to the first match.
- Save the result document with the Document->SaveToFile() method.
The code for finding a single match and reading its information is shown below. In addition to the headers above, it is necessary to include Spire/Doc/Body.h, Spire/Doc/Documents/Paragraph.h, Spire/Doc/Documents/DocumentObjectType.h, and Spire/Doc/Collections/DocumentObjectCollection.h.
// Besides the headers above, also include Body.h, Paragraph.h, DocumentObjectType.h and DocumentObjectCollection.h
int main() {
// Specify the input file path
string inputFile = "QualityReview.docx";
// Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "FirstMatch.docx";
// Create a Document object and load the document
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFile.c_str());
// Find the first occurrence of "deliverable"
intrusive_ptr<TextSelection> selection =
document->FindString("deliverable", false, false);
intrusive_ptr<TextRange> range = selection->GetAsOneRange();
intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();
intrusive_ptr<Body> body = paragraph->GetOwnerTextBody();
// Read the match information
cout << "Matched text: " << selection->GetSelectedText() << endl;
cout << "Range count: " << selection->GetCount() << endl;
cout << "Body object index: " << body->GetChildObjects()->IndexOf(paragraph) << endl;
cout << "Paragraph: " << paragraph->GetText() << endl;
// Highlight only the first match in red
range->GetCharacterFormat()->SetHighlightColor(Color::GetRed());
// Save the document as docx
document->SaveToFile(outputFile.c_str(), FileFormat::Docx);
document->Close();
}
The location information obtained when the sample runs is as follows:
| Item | Value |
|---|---|
| Matched text | deliverable |
| Range count | 1 |
| Body object index | 9 |
| Paragraph | Order volume in the third quarter grew 12% over the previous quarter, and the deliverable schedule accelerated noticeably. … |
After execution, only the first occurrence of "deliverable" is marked red; the other two remain unchanged:

Paragraph Index Counts Body Objects
body->GetChildObjects()->IndexOf(paragraph) returns the position of the paragraph in its body object collection. The collection contains both paragraphs and tables, so index 9 is not the ninth paragraph. The body collection of the sample document consists of the title block, the information strip, the summary box, headings and paragraphs at various levels, the chart, and the table; the first nine objects already include tables and empty paragraphs. When processing by paragraph ordinal, first filter the members whose DocumentObjectType is Paragraph, and then renumber them.
Difference Between FindString and FindAllString
FindString() returns only the first match, which suits confirming whether the target text exists in the document or obtaining the position of the first match; FindAllString() returns all matches, which suits applying formatting in bulk or counting occurrences. Both use the same matching parameters and the same hit rules; they differ only in the number of results returned.
Finding Does Not Change the Text Content
The search itself does not modify the text. The sample only sets the highlight property in CharacterFormat, which is character formatting; paragraph text, table content, and document structure remain unchanged. The saved file can still be edited normally, and the highlighting can be cleared directly in Word.
Get a Free License
If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.
