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.

© SautinSoft 2002 - 2019