前面介绍了如何使用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
效果图: