How to count how many times a specific text 'Tom' appears in the document.
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/help/net/developer-guide/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();
}
}
}
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/help/net/developer-guide/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
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: