
When working with Word templates, it's common to replace specific placeholders with real content—like names, dates, or even company logos. Manually updating each instance may take lots of effort and time. Fortunately, you can automate this process using code. In this tutorial, we'll show you how to use C# regex replace to find and replace text in Word documents. You'll learn how to apply regular expressions across the entire document, target specific paragraphs, and even replace matched text with images.
- Before We Start: Install Word Library
- Replace Text in an Entire Word Document
- Replace Text within Specific Paragraph in C#
- Replace Regex Matches with Images
- Replace Text with Regex in VB.NET
- Conclusion
Before We Start: Install Word Library
To make this task easier, we recommend using Spire.Doc for .NET — a powerful Word library designed to automate common document operations such as reading, editing, and converting Word files. With Spire.Doc, performing a C# regex replace in Word documents can be done in just a few lines of code.
You can install the library via NuGet with the following command:
PM> Install-Package Spire.Doc
Alternatively, you can download the Spire.Doc package and install it with custom settings. A free version is also available, ideal for small projects or evaluation purposes.
Use Regex to Replace Text in an Entire Word Document
Let's start with the most common scenario — replacing text throughout the entire Word document. You can use regular expressions to match all patterns like #name or #tel, then replace them with actual values such as a person's name or phone number.
With the help of the Document.Replace() method provided by Spire.Doc, this task becomes incredibly simple. Here's a step-by-step explanation along with sample code to show how to replace text using regex in C#.
Code example - replacing #name with "May" in the entire Word document using C#:
using Spire.Doc;
using System.Text.RegularExpressions;
namespace FindText
{
class Program
{
static void Main(string[] args)
{
// Create an object of Document class and load a Word document
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
// Set the regular expression
Regex regex = new Regex(@"#\w+\b");
// Replace all matches with "May"
doc.Replace(regex, "May");
// Save the document
doc.SaveToFile("/output/replacealloccurences.docx", FileFormat.Docx2013);
}
}
}
Here is a comparison preview of the results before and after using regex to replace text in C#: 
Steps Explained:
- Create a Document instance and load a Word document from files.
- Set the regular expression.
- Replace all matches in the document with Documet.Replace() method.
- Save the updated document.
Apply Regex Replace to a Specific Paragraph in C#
Replacing text across the entire document may seem straightforward, but how can we achieve the same result within a specific paragraph? When you need more precise control, such as performing regex replace only within a paragraph range, you can retrieve the paragraph text and reset its content manually. In code, this means using regular expressions to locate matches within the target paragraph, remove the original text, and insert the replacement.
Let’s first look at a real-world code example — we’ll break down the detailed steps right after.
Code example - replacing #name with "Lily" in the first paragraph using regular expression:
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a template
Document doc = new Document();
doc.LoadFromFile("/input/replace template.docx");
Regex regex = new Regex(@"#\w+\b");
// Get the first paragraph
Paragraph para = doc.Sections[0].Paragraphs[0];
string originalText = para.Text;
if (regex.IsMatch(originalText))
{
string newText = regex.Replace(originalText, "Lily");
// Clear the content and append the new text
para.ChildObjects.Clear();
para.AppendText(newText);
}
// Save the updated document
doc.SaveToFile("/output/replacefirstpara.docx", FileFormat.Docx2013);
}
}
Here is a before-and-after comparison of using regular expressions in C# to replace text in the first paragraph: 
Detailed steps explained:
- Create a Document object and load the Word file.
- Access the target paragraph using Sections[].Paragraphs[] property.
- Get the original text from the paragraph.
- Use a regular expression to find and replace matching text.
- Clear the original content and append the updated text to the paragraph.
- Save the modified document.
Replace Regex Matches with Images in Word Using C#
Now that we’ve covered how to replace text in the entire document or within a single paragraph, let’s move on to something more advanced—replacing text with images. This is often used in practical scenarios like generating reports or company brochures. For instance, you might want to replace a placeholder such as [logo] with your company’s actual logo.
With the help of C# regex replace and Spire.Doc’s image insertion APIs, this task can also be automated. Let’s take a look at a real code example first, then we’ll explain how it works.
Code example – replacing [avatar] with an image:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace RegexReplaceWithImage
{
class Program
{
static void Main(string[] args)
{
// Create a Document object and load a Word file from disk
Document document = new Document();
document.LoadFromFile(@"\input\replace template.docx");
// Define a regular expression to match placeholders
Regex regex = new Regex(@"\[\w+\]", RegexOptions.IgnoreCase);
// Find all matches in the document that match the pattern
TextSelection[] selections = document.FindAllPattern(regex);
// Loop through each matched placeholder
foreach (TextSelection selection in selections)
{
// Create a picture object and load the image from disk
DocPicture pic = new DocPicture(document);
pic.LoadImage(@"\avatar-1.png");
// Get the matched text as a single text range
TextRange textRange = selection.GetAsOneRange();
// Get the index of the text range in its parent paragraph
int index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange);
// Insert the image at the matched position
textRange.OwnerParagraph.ChildObjects.Insert(index, pic);
// Remove the original placeholder text
textRange.OwnerParagraph.ChildObjects.Remove(textRange);
}
// Save the modified document to disk
document.SaveToFile(@"\output\ReplaceTextWithImage.docx", FileFormat.Docx2016);
document.Close();
}
}
}
Here is a before-and-after comparison of replacing text with an image using regex in C#: 
Detailed steps explained:
- Create an object of Document class and read a Word document.
- Define a regular expression to match target content.
- Find all occurrences using Document.FindAllPattern() method.
- Loop through the collection of matches.
- Create a DocPicture instance and load an image.
- Get the matched text as a text range and retrieve its index in the parent paragraph.
- Insert the image at the position and remove the original text.
- Save the Word document as a new file.
Replace Text with Regex in VB.NET
If you're working with VB.NET instead of C#, you can achieve the same result using regular expressions to search and replace text throughout a Word document. The approach is similar—load the file, apply a regex pattern, and update the content. Here's a simple example to get you started.
Imports Spire.Doc
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim doc As New Document()
doc.LoadFromFile("/input/replace template.docx")
Dim regex As New Regex("#\w+\b")
doc.Replace(regex, "Lena")
doc.SaveToFile("/output/regexreplace.docx", FileFormat.Docx2013)
End Sub
End Module
Above is the VB.NET code for replacing text throughout an entire Word document using regular expressions.
If you need to perform other tasks, such as replacing text in specific paragraphs or replacing text with images, you can easily convert the C# code examples into VB.NET using the C# Code ⇆ VB.NET Code Converter — a handy tool developed by the Spire.Doc team.
The Conclusion
With the help of regular expressions, replacing text or even inserting images in Word documents using C# becomes a smooth and efficient process. Whether you're working on templates, reports, or personalized documents, this approach saves time and reduces manual work. Ready to try it out? Download Spire.Doc and get started with a free 30-day trial license—perfect for evaluation and small projects.
