文檔半島外圍網上直營>>E-iceblue中文文檔>>在 C#、VB.NET 中通過 Word 中的正則表達式查找和替換文本
                在 C#、VB.NET 中通過 Word 中的正則表達式查找和替換文本
Spire.Doc for .NET是一款專門對 Word 文檔進行操作的 .NET 類庫。在于幫助開發人員無需安裝 Microsoft Word情況下,輕松快捷高效地創建、編輯、轉換和打印 Microsoft Word 文檔。擁有近10年專業開發經驗Spire系列辦公文檔開發工具,專注于創建、編輯、轉換和打印Word/PDF/Excel等格式文件處理,小巧便捷。下面我們將給您介紹如何在 C#、VB.NET 中通過 Word 中的正則表達式查找和替換文本。
Spire.Doc 提供了在 Word 文檔中查找與特定正則表達式匹配的單詞并將匹配的單詞替換為新字符串的能力。以下代碼片段給出了一個示例。
第 1 步:創建 Document 對象并加載測試文檔。
Document doc = new Document();
doc.LoadFromFile("example.docx");
第 2 步:為以 # 開頭的單詞定義正則表達式。
Regex regex = new Regex(@"\#\w+\b");
第 3 步:調用 Document.Repalce(Regex pattern, string replace) 方法將匹配的文本替換為新字符串。
doc.Replace(regex, "Spire.Doc");
第 4 步:保存文件。
doc.SaveToFile("output.docx", FileFormat.Docx2013);
結果:
  
 
	
完整代碼:
[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
以上便是如何在 C#、VB.NET 中通過 Word 中的正則表達式查找和替換文本,如果您有其他問題也可以繼續瀏覽本系列文章,獲取相關教程,你還可以給我留言或者加入我們的官方技術交流群。

 QQ交談
QQ交談 在線咨詢
在線咨詢 
                 
                
 渝公網安備
            50010702500608號
渝公網安備
            50010702500608號
             
            
 客服熱線
客服熱線