Document .Net - Find Text

How to find a specific text in DOCX document using C# and VB.Net

How to count how many times a specific text 'Tom' appears in the document.


Complete code

using System;
using System.IO;
using System.Linq;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            FindText();
        }
        /// <summary>
        /// Find a specific text in DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/examples/find-text-in-docx-document-net-csharp-vb.php
        /// </remarks>
        static void FindText()
        {
            string filePath = @"..\..\example.docx";
            DocumentCore dc = DocumentCore.Load(filePath);

            // Searching string.
            string searchText = "Tom";

            // Specify Regex to search with ignore case pattern:
            // "TOM", "ToM", "toM", etc.
            Regex regex = new Regex("(?i)" + searchText);
            int count = dc.Content.Find(regex).Count();

            Console.WriteLine("The text: \"" + searchText + "\" - was found " + count.ToString() + " time(s).");
            Console.ReadKey();
        }
    }
}

Download.

        
            Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document

Module Sample
    Sub Main()
        FindText()
    End Sub

    ''' <summary>
    ''' Find a specific text in DOCX document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/examples/find-text-in-docx-document-net-csharp-vb.php
    ''' </remarks>
    Private Shared Sub FindText()
            Dim filePath As String = "..\example.docx"
            Dim dc As DocumentCore = DocumentCore.Load(filePath)

            ' Searching string.
            Dim searchText As String = "Tom"

            ' Specify Regex to search with ignore case pattern:
            ' "TOM", "ToM", "toM", etc.
            Dim regex As New Regex("(?i)" & searchText)
            Dim count As Integer = dc.Content.Find(regex).Count()

            Console.WriteLine("The text: """ & searchText & """ - was found " & count.ToString() & " time(s).")
            Console.ReadKey()
        End Sub
    End Class
End Namespace

Download.


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.

© SautinSoft 2002 - 2019