查找和替换

您可以使用键盘和鼠标轻松地在文档中导航,但如果您有很多页面需要滚动,则需要相当长的时间才能在长文档中找到特定文本。当您想要替换文档中使用的某些字符或单词时,这会花费更多时间。 “查找和替换"功能使您能够在文档中查找字符序列并将其替换为另一个字符序列。

Aspose.Words 允许您在文档中查找特定字符串或正则表达式模式,并将其替换为替代方案,而无需安装和使用 Microsoft Word 等其他应用程序。这将加快许多打字和格式化任务的速度,可能会节省您的工作时间。

本文介绍如何在元字符的支持下应用字符串替换和正则表达式。

查找和替换 {#ways-to-find-and-replace} 的方法

Aspose.Words 提供了两种应用查找和替换操作的方法,方法如下:

  1. 简单字符串替换 – 要查找特定字符串并将其替换为另一个字符串,您需要指定一个搜索字符串(字母数字字符),该搜索字符串将根据所有出现的情况被替换为另一个指定的替换字符串。两个字符串都不能包含符号。请考虑到字符串比较可能区分大小写,否则您可能不确定拼写或有多个相似的拼写。
  2. 正则表达式 – 指定正则表达式来查找精确匹配的字符串并根据您的正则表达式替换它们。请注意,单词被定义为仅由字母数字字符组成。如果仅匹配整个单词而执行替换,并且输入字符串恰好包含符号,则将找不到短语。

此外,您可以使用带有简单字符串替换和正则表达式的特殊元字符来指定查找和替换操作中的中断。

Aspose.Words 通过 Aspose.Words.Replacing 命名空间提供查找和替换功能。您可以在使用 FindReplaceOptions 类的查找和替换过程中使用许多选项。

使用简单字符串替换 {#find-and-replace-text-using-simple-string-replacement} 查找和替换文本

您可以使用 Replace 方法之一来查找或替换特定字符串并返回所做的替换数。在这种情况下,您可以指定要替换的字符串、将替换所有出现的字符串、替换是否区分大小写以及是否仅影响独立单词。

以下代码示例显示如何查找字符串”CustomerName“并将其替换为字符串*“James Bond”*:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load a Word Docx document by creating an instance of the Document class.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello _CustomerName_,");
// Specify the search string and replace string using the Replace method.
doc.Range.Replace("_CustomerName_", "James Bond", new FindReplaceOptions());
// Save the result.
doc.Save(dataDir + "Range.ReplaceSimple.docx");

在应用简单字符串替换之前,您可以注意到文档之间的差异:

简单字符串替换之前

应用简单的字符串替换后:

简单字符串替换后

使用正则表达式 {#find-and-replace-text-using-regular-expressions} 查找和替换文本

正则表达式 (regex) 是描述特定文本序列的模式。假设您要将某个单词的所有重复出现替换为单个单词出现。然后,您可以应用以下正则表达式来指定双字模式:([a-zA-Z]+) \1

使用其他 Replace 方法通过将 Regex 参数设置为正则表达式模式来搜索和替换特定字符组合以查找匹配项。

以下代码示例演示如何将与正则表达式模式匹配的字符串替换为指定的替换字符串:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("sad mad bad");
Assert.AreEqual("sad mad bad", doc.GetText().Trim());
// Replaces all occurrences of the words "sad" or "mad" to "bad".
doc.Range.Replace(new Regex("[s|m]ad"), "bad");
// Save the Word document.
doc.Save("Range.ReplaceWithRegex.docx");

在使用正则表达式进行字符串替换之前,您可以注意到文档之间的差异:

用正则表达式替换之前

使用正则表达式应用字符串替换后:

用正则表达式替换后

使用元字符 {#find-and-replace-text-using-metacharacters} 查找和替换字符串

如果特定文本或短语由多个段落、部分或页面组成,则可以在搜索字符串或替换字符串中使用元字符。一些元字符包括用于段落分隔符的 &p、用于分节符的 &b、用于分页符的 和米 以及用于换行符的 &l

以下代码示例演示如何用段落和分页符替换文本:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("First section");
builder.Writeln(" 1st paragraph");
builder.Writeln(" 2nd paragraph");
builder.Writeln("{insert-section}");
builder.Writeln("Second section");
builder.Writeln(" 1st paragraph");
FindReplaceOptions options = new FindReplaceOptions();
options.ApplyParagraphFormat.Alignment = ParagraphAlignment.Center;
// Double each paragraph break after word "section", add kind of underline and make it centered.
int count = doc.Range.Replace("section&p", "section&p----------------------&p", options);
// Insert section break instead of custom text tag.
count = doc.Range.Replace("{insert-section}", "&b", options);
dataDir = dataDir + "ReplaceTextContaingMetaCharacters_out.docx";
doc.Save(dataDir);

您可以使用 HeaderFooter 类查找并替换 Word 文档的页眉/页脚部分中的文本。

以下代码示例演示如何替换文档中标题部分的文本:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(dataDir + "HeaderFooter.ReplaceText.doc");
// Access header of the Word document.
HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter header = headersFooters[HeaderFooterType.HeaderPrimary];
// Set options.
FindReplaceOptions options = new FindReplaceOptions
{
MatchCase = false,
FindWholeWordsOnly = false
};
// Replace text in the header of the Word document.
header.Range.Replace("Aspose.Words", "Remove", options);
// Save the Word document.
doc.Save(dataDir + "HeaderReplace.docx");

您可以在应用标题字符串替换之前注意到文档之间的差异:

应用标头字符串替换之前

应用标头字符串替换后:

应用标头字符串替换后

用于替换文档中页脚部分文本的代码示例与前面的页眉代码示例非常相似。您需要做的就是替换以下两行:

HeaderFooter header = headersFooters[HeaderFooterType.HeaderPrimary];
header.Range.Replace("Aspose.Words", "Remove", options);

具有以下内容:

HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];
int currentYear = System.DateTime.Now.Year;
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", $"Copyright (C) {currentYear} by Aspose Pty Ltd.", options);

在应用页脚字符串替换之前,您可以注意到文档之间的差异:

应用页脚字符串替换之前

应用页脚字符串替换后:

应用页脚字符串替换后

在查找和替换 {#ignore-text-during-find-and-replace} 期间忽略文本

在应用查找和替换操作时,您可以忽略文本的某些片段。因此,可以从搜索中排除文本的某些部分,并且查找和替换只能应用于其余部分。

Aspose.Words 提供了许多用于忽略文本的查找和替换属性,例如 IgnoreDeletedIgnoreFieldCodesIgnoreFieldsIgnoreFootnotesIgnoreInserted

以下代码示例显示如何忽略删除修订中的文本:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert non-revised text.
builder.Writeln("Deleted");
builder.Write("Text");
// Remove first paragraph with tracking revisions.
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.FirstSection.Body.FirstParagraph.Remove();
doc.StopTrackRevisions();
Regex regex = new Regex("e");
FindReplaceOptions options = new FindReplaceOptions();
// Replace 'e' in document while ignoring deleted text.
options.IgnoreDeleted = true;
doc.Range.Replace(regex, "*", options);
Assert.AreEqual(doc.GetText().Trim(), "Deleted\rT*xt");
// Replace 'e' in document while not ignoring deleted text.
options.IgnoreDeleted = false;
doc.Range.Replace(regex, "*", options);

自定义查找和替换操作

Aspose.Words 提供了许多不同的 properties 来查找和替换文本,例如使用 ApplyFontApplyParagraphFormats 属性应用特定格式、使用 UseSubstitutions 属性在替换模式中使用替换等。

以下代码示例演示如何突出显示文档中的特定单词:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Highlight word "the" with yellow color.
FindReplaceOptions options = new FindReplaceOptions();
options.ApplyFont.HighlightColor = Color.Yellow;
// Replace highlighted text.
doc.Range.Replace("Hello", "Hello", options);

Aspose.Words 允许您在替换操作期间使用 IReplacingCallback 接口创建和调用自定义方法。您可能有一些需要自定义查找和替换操作的用例,例如用 HTML 标记替换用正则表达式指定的文本,因此基本上您将通过插入 HTML 来应用替换。

如果您需要用 HTML 标记替换字符串,请应用 IReplacingCallback 接口来自定义查找和替换操作,以便匹配从文档的匹配节点开始运行。让我们提供几个使用 IReplacingCallback 的示例。

以下代码示例显示如何替换用 HTML 指定的文本:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void ReplaceWithHtml(string dataDir)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello <CustomerName>,");
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);
doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);
// Save the modified document.
doc.Save(dataDir + "Range.ReplaceWithInsertHtml.doc");
}
private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
{
mOptions = options;
}
//This simplistic method will only work well when the match starts at the beginning of a run.
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
builder.MoveTo(args.MatchNode);
// Replace '<CustomerName>' text with a red bold name.
builder.InsertHtml("<b><font color='red'>James Bond, </font></b>"); args.Replacement = "";
return ReplaceAction.Replace;
}
private readonly FindReplaceOptions mOptions;
}

以下代码示例演示如何用绿色突出显示正数,用红色突出显示负数:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Replace and Highlight Numbers.
internal class NumberHighlightCallback : IReplacingCallback
{
public NumberHighlightCallback(FindReplaceOptions opt)
{
mOpt = opt;
}
public ReplaceAction Replacing(ReplacingArgs args)
{
// Let replacement to be the same text.
args.Replacement = args.Match.Value;
int val = int.Parse(args.Match.Value);
// Apply either red or green color depending on the number value sign.
mOpt.ApplyFont.Color = (val > 0)
? Color.Green
: Color.Red;
return ReplaceAction.Replace;
}
private readonly FindReplaceOptions mOpt;
}

以下代码示例显示如何在每行前面添加行号:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public void LineCounter()
{
// Create a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add lines of text.
builder.Writeln("This is first line");
builder.Writeln("Second line");
builder.Writeln("And last line");
// Prepend each line with line number.
FindReplaceOptions opt = new FindReplaceOptions() { ReplacingCallback = new LineCounterCallback() };
doc.Range.Replace(new Regex("[^&p]*&p"), "", opt);
doc.Save(@"X:\TestLineCounter.docx");
}
internal class LineCounterCallback : IReplacingCallback
{
public ReplaceAction Replacing(ReplacingArgs args)
{
Debug.WriteLine(args.Match.Value);
args.Replacement = string.Format("{0} {1}", mCounter++, args.Match.Value);
return ReplaceAction.Replace;
}
private int mCounter = 1;
}