前面介绍了如何使用Spire.Doc for .NET实现 Word查找、替换和高亮显示功能。该文将介绍如何使用正则表达式查找和替换Word 文档中的文本。
请查看示例文档:
C#
using Spire.Doc;
using System.Text.RegularExpressions;
using System.Drawing;
namespace WordDemo
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
//替换以#开头的字符
Regex regex = new Regex(@"\#\w+\b");
doc.Replace(regex, "Spire.Doc");
//替换[]内的字符
Regex regex1 = new Regex(@"[[\s\S]*]");
doc.Replace(regex1, "Spire.Doc for .NET");
//保存文档
doc.SaveToFile("Result.docx", FileFormat.Docx2013);
}
}
}
VB.NET
Imports Spire.Doc
Imports System.Text.RegularExpressions
Imports System.Drawing
Namespace WordDemo
Class Program
Private Shared Sub Main(ByVal args() As String)
Dim doc As Document = New Document
doc.LoadFromFile("Sample.docx")
'替换以#开头的字符
Dim regex As Regex = New Regex("\#\w+\b")
doc.Replace(regex, "Spire.Doc")
'替换[]内的字符
Dim regex1 As Regex = New Regex("[[\s\S]*]")
doc.Replace(regex1, "Spire.Doc for .NET")
'保存文档
doc.SaveToFile("Result.docx", FileFormat.Docx2013)
End Sub
End Class
End Namespace
效果图: