Find and Replace Text by Regular Expressions in Word in C#, VB.NET

Spire.Doc provides the ability to find the words that match a specific regular expression in a Word document and replace the matched words with a new string. This following code snippets give an example.

Step 1: Create an object of Document and load a test document.

Document doc = new Document();
doc.LoadFromFile("example.docx");

Step 2: Define a regular expression for the words that start with #.

Regex regex = new Regex(@"\#\w+\b");

Step 3: Call Document.Repalce(Regex pattern, string replace) method to replace the matched text with a new string.

doc.Replace(regex, "Spire.Doc");

Step 4: Save the file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Result:

How to Find and Replace Text by Regular Expressions in Word in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("example.docx");
            Regex regex = new Regex(@"\#\w+\b");
            doc.Replace(regex, "Spire.Doc");
            doc.SaveToFile("output.docx", FileFormat.Docx2013);
        }
    }
[VB.NET]
Imports Spire.Doc
Imports System.Text.RegularExpressions
Namespace FindText
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("example.docx")
			Dim regex As New Regex("\#\w+\b")
			doc.Replace(regex, "Spire.Doc")
			doc.SaveToFile("output.docx", FileFormat.Docx2013)
		End Sub
	End Class
End Namespace