Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/aa74a6af7dc0a12f98ae335ff7543aa5 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/aa74a6af7dc0a12f98ae335ff7543aa5 to your computer and use it in GitHub Desktop.
NET的Aspose.Words-查找和替换文本
// 加载Word docx文档
Document doc = new Document("document.docx");
FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = true;
// 查找并替换文档中的文本
doc.Range.Replace(new Regex("[B|S|M]ad"), "[replaced]", options);
// 保存Word文档
doc.Save("Find-And-Replace-Multiple-Words.docx");
// 加载Word docx文档
Document doc = new Document("document.docx");
FindReplaceOptions options = new FindReplaceOptions();
options.FindWholeWordsOnly = true;
// 设置电子邮件ID的正则表达式
Regex EmailRegex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
// 查找并替换文档中的文本
doc.Range.Replace(EmailRegex, "[replaced]", options);
// 保存Word文档
doc.Save("Find-And-Replace-Text-Using-Regex.docx");
// 加载Word文档
Document doc = new Document("document.docx");
// 访问Word文档的页眉/页脚
HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];
// 设定选项
FindReplaceOptions options = new FindReplaceOptions
{
MatchCase = false,
FindWholeWordsOnly = false
};
// 替换Word文档页脚中的文本
footer.Range.Replace("This is footer of the document.", "Copyright (C) 2020 by Aspose Pty Ltd.", options);
// 保存Word文档
doc.Save("Find-And-Replace-Text-in-Footer.docx");
// 加载Word docx文档
Document doc = new Document("document.docx");
// 设定选项
FindReplaceOptions options = new FindReplaceOptions
{
MatchCase = false,
FindWholeWordsOnly = false
};
// 用段落分隔符替换文本
doc.Range.Replace("First paragraph ends.&pSecond paragraph starts.", "[replaced]", options);
// 保存Word文档
doc.Save("Find-And-Replace-Text-Paragraph-Break.docx");
// 加载Word docx文档
Document doc = new Document("document.docx");
// 查找并替换文档中的文本
doc.Range.Replace("sad", "[replaced]", new FindReplaceOptions(FindReplaceDirection.Forward));
// 保存Word文档
doc.Save("Find-And-Replace-Text.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment