Discover the magic of programmatic regex search! In the world of coding, regular expressions are like secret codes that help us find specific information in text. This article will show you how to search by regex in C# to search documents of various file formats smartly.
.NET API for Regex Search in Documents by Regex
For Regex Search, we’ll utilize the GroupDocs.Search for .NET API. This allows us to search text within files of various formats across folders just by providing the regex pattern. This library empowers us to programmatically search text in a wide range of file formats, such as Word documents, spreadsheets, presentations, PDF files, Markup files, eBooks, email messages, One Note documents, and ZIP archives.
For an in-depth list of supported file formats, refer to the comprehensive documentation.
You can download the API from the releases page, or you can install it into your .NET application using NuGet. The code examples in this article use the API of GroupDocs.Search for .NET 26.10 and the namespaces GroupDocs.Search, GroupDocs.Search.Common, GroupDocs.Search.Highlighters, GroupDocs.Search.Options and GroupDocs.Search.Results.
PM> Install-Package GroupDocs.Search
How to Search in Files by Regex using C#
Follow these steps to perform a regex search in multiple files of various file formats within folders using C#: Later you can easily generate the highlighted HTML output files for each found document.
- Create an Index by providing a folder path.
- Add the path of the parent folder for the search directory to the created index.
- Define the regex search query.
- Execute the search using the Search method to get the search results.
- Now you can iterate on the SearchResult to create an output as you like.
The regex used in the below-mentioned code identifies all the words having consecutive repeated characters like; added, wood, and see. The following C# code performs the quick search by regex in multiple files of different file formats across folders.
string indexFolder = @"c:\MyIndex\"; // Specify path to the index folder
string documentsFolder = @"c:\MyDocuments\"; // Specify path to the parent folder with documents
string outputFolder = @"c:\Output\"; // Specify path to the folder for the HTML files
// Creating an index in the specified folder
Index index = new Index(indexFolder);
// Indexing the parent folder; documents in the subfolders are indexed as well
index.Add(documentsFolder);
// Defining a regex search query for words with two identical consecutive characters
// The regular expression is matched against each word of the index
SearchQuery query = SearchQuery.CreateRegexQuery(@"(.)\1");
// Searching in the index
SearchResult result = index.Search(query);
// Creating the output folder
Directory.CreateDirectory(outputFolder);
for (int i = 0; i < result.DocumentCount; i++)
{
// Getting the found document
FoundDocument document = result.GetFoundDocument(i);
// Setting up the output adapter for an HTML file named after the document
string outputPath = Path.Combine(outputFolder, Path.GetFileName(document.DocumentInfo.FilePath) + ".html");
FileOutputAdapter outputAdapter = new FileOutputAdapter(OutputFormat.Html, outputPath);
// Creating the highlighter and generating the text with the highlighted occurrences
Highlighter highlighter = new DocumentHighlighter(outputAdapter);
index.Highlight(document, highlighter);
}
Here I have highlighted the regex search results of the above code:
Printing Search Results
The following C# code provides two ways to present your search results.
- Highlight all the found words.
- Print in a readable and analyzable format
// The 'result' object is taken from the previous example
for (int i = 0; i < result.DocumentCount; i++)
{
FoundDocument document = result.GetFoundDocument(i);
Console.WriteLine("Document: " + Path.GetFileName(document.DocumentInfo.FilePath));
Console.WriteLine("Occurrences: " + document.OccurrenceCount);
for (int j = 0; j < document.FoundFields.Length; j++)
{
FoundDocumentField field = document.FoundFields[j];
Console.WriteLine("\tField: " + field.FieldName);
Console.WriteLine("\tOccurrences: " + field.OccurrenceCount);
// Printing the found words with the number of their occurrences
for (int k = 0; k < field.Terms.Length; k++)
{
Console.WriteLine("\t\t" + field.Terms[k].PadRight(20) + field.TermsOccurrences[k]);
}
}
Console.WriteLine("===========================================");
}
Since version 26.10, regular expression search uses all processor cores by default, so the order of the found words may differ from run to run. To get the same order every time, set the SearchThreads index setting to NumberOfThreads.One.
Document: English.txt
Occurrences: 83
Field: content
Occurrences: 82
acceptance 1
added 1
agreeable 1
agreed 1
all 4
appearance 1
assurance 1
...
===========================================
Document: Lorem ipsum.docx
Occurrences: 945
Field: content
Occurrences: 939
accumsan 39
class 7
commodo 40
convallis 38
dignissim 35
efficitur 46
fringilla 40
habitasse 2
laoreet 27
massa 63
mattis 31
...
Getting a Free License or a Free Trial
Free License
Obtain a temporary license for free to explore this library without constraints.
Free Trial
You can download the free trial from the releases page.
Conclusion
In this article, we looked into the magic of RegEx search to find all the words having a certain pattern within various text-based documents like DOCX, PDF, and TXT files across several folders using C#. Afterward, we presented the search results by highlighting the searched words and by printing them in a readable format.
For comprehensive details about the API, readers are advised to refer to the documentation.
Any inquiries or additional discussions can be directed to the available forum.