Class FindReplaceOptions

Class FindReplaceOptions

Namespace: Aspose.Words.Replacing
Assembly: Aspose.Words.dll (25.12.0)

Specifies options for find/replace operations.

To learn more, visit the Find and Replace documentation article.

public class FindReplaceOptions

Inheritance

object FindReplaceOptions

Inherited Members

object.GetType() , object.MemberwiseClone() , object.ToString() , object.Equals(object?) , object.Equals(object?, object?) , object.ReferenceEquals(object?, object?) , object.GetHashCode()

Examples

Shows how to toggle case sensitivity when performing a find-and-replace operation.

Document doc = new Document();
                                                                                             DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                             builder.Writeln("Ruby bought a ruby necklace.");

                                                                                             // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                             FindReplaceOptions options = new FindReplaceOptions();

                                                                                             // Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
                                                                                             // Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
                                                                                             options.MatchCase = matchCase;

                                                                                             doc.Range.Replace("Ruby", "Jade", options);

                                                                                             Assert.That(doc.GetText().Trim(), Is.EqualTo(matchCase ? "Jade bought a ruby necklace." : "Jade bought a Jade necklace."));

Shows how to toggle standalone word-only find-and-replace operations.

Document doc = new Document();
                                                                                DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                builder.Writeln("Jackson will meet you in Jacksonville.");

                                                                                // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                FindReplaceOptions options = new FindReplaceOptions();

                                                                                // Set the "FindWholeWordsOnly" flag to "true" to replace the found text if it is not a part of another word.
                                                                                // Set the "FindWholeWordsOnly" flag to "false" to replace all text regardless of its surroundings.
                                                                                options.FindWholeWordsOnly = findWholeWordsOnly;

                                                                                doc.Range.Replace("Jackson", "Louis", options);

                                                                                Assert.That(doc.GetText().Trim(), Is.EqualTo(findWholeWordsOnly ? "Louis will meet you in Jacksonville." : "Louis will meet you in Louisville."));

Constructors

FindReplaceOptions()

Initializes a new instance of the FindReplaceOptions class with default settings.

public FindReplaceOptions()

Examples

Shows how to recognize and use substitutions within replacement patterns.

Document doc = new Document();
                                                                                    DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                    builder.Write("Jason gave money to Paul.");

                                                                                    Regex regex = new Regex(@"([A-z]+) gave money to ([A-z]+)");

                                                                                    FindReplaceOptions options = new FindReplaceOptions();
                                                                                    options.UseSubstitutions = true;

                                                                                    // Using legacy mode does not support many advanced features, so we need to set it to 'false'.
                                                                                    options.LegacyMode = false;

                                                                                    doc.Range.Replace(regex, @"$2 took money from $1", options);

                                                                                    Assert.That("Paul took money from Jason.\f", Is.EqualTo(doc.GetText()));

FindReplaceOptions(FindReplaceDirection)

Initializes a new instance of the FindReplaceOptions class with the specified direction.

public FindReplaceOptions(FindReplaceDirection direction)

Parameters

direction FindReplaceDirection

The direction of the find and replace operation.

FindReplaceOptions(IReplacingCallback)

Initializes a new instance of the FindReplaceOptions class with the specified replacing callback.

public FindReplaceOptions(IReplacingCallback replacingCallback)

Parameters

replacingCallback IReplacingCallback

The callback to use for replacing found text.

Examples

Shows how to track the order in which a text replacement operation traverses nodes.

public void Order(bool differentFirstPageHeaderFooter)
                                                                                              {
                                                                                                  Document doc = new Document(MyDir + "Header and footer types.docx");

                                                                                                  Section firstPageSection = doc.FirstSection;

                                                                                                  ReplaceLog logger = new ReplaceLog();
                                                                                                  FindReplaceOptions options = new FindReplaceOptions(logger);

                                                                                                  // Using a different header/footer for the first page will affect the search order.
                                                                                                  firstPageSection.PageSetup.DifferentFirstPageHeaderFooter = differentFirstPageHeaderFooter;
                                                                                                  doc.Range.Replace(new Regex("(header|footer)"), "", options);

                                                                                                  if (differentFirstPageHeaderFooter)
                                                                                                      Assert.That(logger.Text.Replace("\r", ""), Is.EqualTo("First header\nFirst footer\nSecond header\nSecond footer\nThird header\nThird footer\n"));
                                                                                                  else
                                                                                                      Assert.That(logger.Text.Replace("\r", ""), Is.EqualTo("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\nSecond footer\n"));
                                                                                              }

                                                                                              /// <summary>
                                                                                              /// During a find-and-replace operation, records the contents of every node that has text that the operation 'finds',
                                                                                              /// in the state it is in before the replacement takes place.
                                                                                              /// This will display the order in which the text replacement operation traverses nodes.
                                                                                              /// </summary>
                                                                                              private class ReplaceLog : IReplacingCallback
                                                                                              {
                                                                                                  public ReplaceAction Replacing(ReplacingArgs args)
                                                                                                  {
                                                                                                      mTextBuilder.AppendLine(args.MatchNode.GetText());
                                                                                                      return ReplaceAction.Skip;
                                                                                                  }

                                                                                                  internal string Text => mTextBuilder.ToString();

                                                                                                  private readonly StringBuilder mTextBuilder = new StringBuilder();
                                                                                              }

FindReplaceOptions(FindReplaceDirection, IReplacingCallback)

Initializes a new instance of the FindReplaceOptions class with the specified direction and replacing callback.

public FindReplaceOptions(FindReplaceDirection direction, IReplacingCallback replacingCallback)

Parameters

direction FindReplaceDirection

The direction of the find and replace operation.

replacingCallback IReplacingCallback

The callback to use for replacing found text.

Properties

ApplyFont

Text formatting applied to new content.

public Font ApplyFont { get; }

Property Value

Font

Examples

Shows how to apply a different font to new content via FindReplaceOptions.

public void ConvertNumbersToHexadecimal()
                                                                                     {
                                                                                         Document doc = new Document();
                                                                                         DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                         builder.Font.Name = "Arial";
                                                                                         builder.Writeln("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\n" +
                                                                                                         "123, 456, 789 and 17379.");

                                                                                         // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                         FindReplaceOptions options = new FindReplaceOptions();

                                                                                         // Set the "HighlightColor" property to a background color that we want to apply to the operation's resulting text.
                                                                                         options.ApplyFont.HighlightColor = Color.LightGray;

                                                                                         NumberHexer numberHexer = new NumberHexer();
                                                                                         options.ReplacingCallback = numberHexer;

                                                                                         int replacementCount = doc.Range.Replace(new Regex("[0-9]+"), "", options);

                                                                                         Console.WriteLine(numberHexer.GetLog());

                                                                                         Assert.That(replacementCount, Is.EqualTo(4));
                                                                                         Assert.That(doc.GetText().Trim(), Is.EqualTo("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\r" +
                                                                                                         "0x7B, 0x1C8, 0x315 and 0x43E3."));
                                                                                         Assert.That(doc.GetChildNodes(NodeType.Run, true).OfType<Run>()
                                                                                                 .Count(r => r.Font.HighlightColor.ToArgb() == Color.LightGray.ToArgb()), Is.EqualTo(4));
                                                                                     }

                                                                                     /// <summary>
                                                                                     /// Replaces numeric find-and-replacement matches with their hexadecimal equivalents.
                                                                                     /// Maintains a log of every replacement.
                                                                                     /// </summary>
                                                                                     private class NumberHexer : IReplacingCallback
                                                                                     {
                                                                                         public ReplaceAction Replacing(ReplacingArgs args)
                                                                                         {
                                                                                             mCurrentReplacementNumber++;

                                                                                             int number = Convert.ToInt32(args.Match.Value);

                                                                                             args.Replacement = $"0x{number:X}";

                                                                                             mLog.AppendLine($"Match #{mCurrentReplacementNumber}");
                                                                                             mLog.AppendLine($"\tOriginal value:\t{args.Match.Value}");
                                                                                             mLog.AppendLine($"\tReplacement:\t{args.Replacement}");
                                                                                             mLog.AppendLine($"\tOffset in parent {args.MatchNode.NodeType} node:\t{args.MatchOffset}");

                                                                                             mLog.AppendLine(string.IsNullOrEmpty(args.GroupName)
                                                                                                 ? $"\tGroup index:\t{args.GroupIndex}"
                                                                                                 : $"\tGroup name:\t{args.GroupName}");

                                                                                             return ReplaceAction.Replace;
                                                                                         }

                                                                                         public string GetLog()
                                                                                         {
                                                                                             return mLog.ToString();
                                                                                         }

                                                                                         private int mCurrentReplacementNumber;
                                                                                         private readonly StringBuilder mLog = new StringBuilder();
                                                                                     }

ApplyParagraphFormat

Paragraph formatting applied to new content.

public ParagraphFormat ApplyParagraphFormat { get; }

Property Value

ParagraphFormat

Examples

Shows how to add formatting to paragraphs in which a find-and-replace operation has found matches.

Document doc = new Document();
                                                                                                             DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                             builder.Writeln("Every paragraph that ends with a full stop like this one will be right aligned.");
                                                                                                             builder.Writeln("This one will not!");
                                                                                                             builder.Write("This one also will.");

                                                                                                             ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

                                                                                                             Assert.That(paragraphs[0].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Left));
                                                                                                             Assert.That(paragraphs[1].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Left));
                                                                                                             Assert.That(paragraphs[2].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Left));

                                                                                                             // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                                             FindReplaceOptions options = new FindReplaceOptions();

                                                                                                             // Set the "Alignment" property to "ParagraphAlignment.Right" to right-align every paragraph
                                                                                                             // that contains a match that the find-and-replace operation finds.
                                                                                                             options.ApplyParagraphFormat.Alignment = ParagraphAlignment.Right;

                                                                                                             // Replace every full stop that is right before a paragraph break with an exclamation point.
                                                                                                             int count = doc.Range.Replace(".&p", "!&p", options);

                                                                                                             Assert.That(count, Is.EqualTo(2));
                                                                                                             Assert.That(paragraphs[0].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Right));
                                                                                                             Assert.That(paragraphs[1].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Left));
                                                                                                             Assert.That(paragraphs[2].ParagraphFormat.Alignment, Is.EqualTo(ParagraphAlignment.Right));
                                                                                                             Assert.That(doc.GetText().Trim(), Is.EqualTo("Every paragraph that ends with a full stop like this one will be right aligned!\r" +
                                                                                                                             "This one will not!\r" +
                                                                                                                             "This one also will!"));

Direction

Selects direction for replace. Default value is Aspose.Words.Replacing.FindReplaceDirection.Forward.

public FindReplaceDirection Direction { get; set; }

Property Value

FindReplaceDirection

Examples

Shows how to determine which direction a find-and-replace operation traverses the document in.

public void Direction(FindReplaceDirection findReplaceDirection)
                                                                                                         {
                                                                                                             Document doc = new Document();
                                                                                                             DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                             // Insert three runs which we can search for using a regex pattern.
                                                                                                             // Place one of those runs inside a text box.
                                                                                                             builder.Writeln("Match 1.");
                                                                                                             builder.Writeln("Match 2.");
                                                                                                             builder.Writeln("Match 3.");
                                                                                                             builder.Writeln("Match 4.");

                                                                                                             // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                                             FindReplaceOptions options = new FindReplaceOptions();

                                                                                                             // Assign a custom callback to the "ReplacingCallback" property.
                                                                                                             TextReplacementRecorder callback = new TextReplacementRecorder();
                                                                                                             options.ReplacingCallback = callback;

                                                                                                             // Set the "Direction" property to "FindReplaceDirection.Backward" to get the find-and-replace
                                                                                                             // operation to start from the end of the range, and traverse back to the beginning.
                                                                                                             // Set the "Direction" property to "FindReplaceDirection.Forward" to get the find-and-replace
                                                                                                             // operation to start from the beginning of the range, and traverse to the end.
                                                                                                             options.Direction = findReplaceDirection;

                                                                                                             doc.Range.Replace(new Regex(@"Match \d*"), "Replacement", options);

                                                                                                             Assert.That(doc.GetText().Trim(), Is.EqualTo("Replacement.\r" +
                                                                                                                             "Replacement.\r" +
                                                                                                                             "Replacement.\r" +
                                                                                                                             "Replacement."));

                                                                                                             switch (findReplaceDirection)
                                                                                                             {
                                                                                                                 case FindReplaceDirection.Forward:
                                                                                                                     Assert.That(callback.Matches, Is.EqualTo(new[] { "Match 1", "Match 2", "Match 3", "Match 4" }));
                                                                                                                     break;
                                                                                                                 case FindReplaceDirection.Backward:
                                                                                                                     Assert.That(callback.Matches, Is.EqualTo(new[] { "Match 4", "Match 3", "Match 2", "Match 1" }));
                                                                                                                     break;
                                                                                                             }
                                                                                                         }

                                                                                                         /// <summary>
                                                                                                         /// Records all matches that occur during a find-and-replace operation in the order that they take place.
                                                                                                         /// </summary>
                                                                                                         private class TextReplacementRecorder : IReplacingCallback
                                                                                                         {
                                                                                                             ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
                                                                                                             {
                                                                                                                 Matches.Add(e.Match.Value);
                                                                                                                 return ReplaceAction.Replace;
                                                                                                             }

                                                                                                             public List<string> Matches { get; } = new List<string>();
                                                                                                         }

FindWholeWordsOnly

True indicates the oldValue must be a standalone word.

public bool FindWholeWordsOnly { get; set; }

Property Value

bool

Examples

Shows how to toggle standalone word-only find-and-replace operations.

Document doc = new Document();
                                                                                DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                builder.Writeln("Jackson will meet you in Jacksonville.");

                                                                                // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                FindReplaceOptions options = new FindReplaceOptions();

                                                                                // Set the "FindWholeWordsOnly" flag to "true" to replace the found text if it is not a part of another word.
                                                                                // Set the "FindWholeWordsOnly" flag to "false" to replace all text regardless of its surroundings.
                                                                                options.FindWholeWordsOnly = findWholeWordsOnly;

                                                                                doc.Range.Replace("Jackson", "Louis", options);

                                                                                Assert.That(doc.GetText().Trim(), Is.EqualTo(findWholeWordsOnly ? "Louis will meet you in Jacksonville." : "Louis will meet you in Louisville."));

IgnoreDeleted

Gets or sets a boolean value indicating either to ignore text inside delete revisions. The default value is false.

public bool IgnoreDeleted { get; set; }

Property Value

bool

Examples

Shows how to include or ignore text inside delete revisions during a find-and-replace operation.

Document doc = new Document();
                                                                                                           DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                           builder.Writeln("Hello world!");
                                                                                                           builder.Writeln("Hello again!");

                                                                                                           // Start tracking revisions and remove the second paragraph, which will create a delete revision.
                                                                                                           // That paragraph will persist in the document until we accept the delete revision.
                                                                                                           doc.StartTrackRevisions("John Doe", DateTime.Now);
                                                                                                           doc.FirstSection.Body.Paragraphs[1].Remove();
                                                                                                           doc.StopTrackRevisions();

                                                                                                           Assert.That(doc.FirstSection.Body.Paragraphs[1].IsDeleteRevision, Is.True);

                                                                                                           // We can use a "FindReplaceOptions" object to modify the find and replace process.
                                                                                                           FindReplaceOptions options = new FindReplaceOptions();

                                                                                                           // Set the "IgnoreDeleted" flag to "true" to get the find-and-replace
                                                                                                           // operation to ignore paragraphs that are delete revisions.
                                                                                                           // Set the "IgnoreDeleted" flag to "false" to get the find-and-replace
                                                                                                           // operation to also search for text inside delete revisions.
                                                                                                           options.IgnoreDeleted = ignoreTextInsideDeleteRevisions;

                                                                                                           doc.Range.Replace("Hello", "Greetings", options);

                                                                                                           Assert.That(doc.GetText().Trim(), Is.EqualTo(ignoreTextInsideDeleteRevisions
                                                                                                                   ? "Greetings world!\rHello again!"
                                                                                                                   : "Greetings world!\rGreetings again!"));

IgnoreFieldCodes

Gets or sets a boolean value indicating either to ignore text inside field codes. The default value is false.

public bool IgnoreFieldCodes { get; set; }

Property Value

bool

Examples

Shows how to ignore text inside field codes.

Document doc = new Document();
                                                       DocumentBuilder builder = new DocumentBuilder(doc);

                                                       builder.InsertField("INCLUDETEXT", "Test IT!");

                                                       FindReplaceOptions options = new FindReplaceOptions {IgnoreFieldCodes = ignoreFieldCodes};

                                                       // Replace 'T' in document ignoring text inside field code or not.
                                                       doc.Range.Replace(new Regex("T"), "*", options);
                                                       Console.WriteLine(doc.GetText());

                                                       Assert.That(doc.GetText().Trim(), Is.EqualTo(ignoreFieldCodes
                                                               ? "\u0013INCLUDETEXT\u0014*est I*!\u0015"
                                                               : "\u0013INCLUDE*EX*\u0014*est I*!\u0015"));

Remarks

This option affects only field codes (it does not ignore nodes between Aspose.Words.NodeType.FieldSeparator and Aspose.Words.NodeType.FieldEnd).

To ignore whole field, please use corresponding option Aspose.Words.Replacing.FindReplaceOptions.IgnoreFields.

IgnoreFields

Gets or sets a boolean value indicating either to ignore text inside fields. The default value is false.

public bool IgnoreFields { get; set; }

Property Value

bool

Examples

Shows how to ignore text inside fields.

Document doc = new Document();
                                                  DocumentBuilder builder = new DocumentBuilder(doc);

                                                  builder.Writeln("Hello world!");
                                                  builder.InsertField("QUOTE", "Hello again!");

                                                  // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                  FindReplaceOptions options = new FindReplaceOptions();

                                                  // Set the "IgnoreFields" flag to "true" to get the find-and-replace
                                                  // operation to ignore text inside fields.
                                                  // Set the "IgnoreFields" flag to "false" to get the find-and-replace
                                                  // operation to also search for text inside fields.
                                                  options.IgnoreFields = ignoreTextInsideFields;

                                                  doc.Range.Replace("Hello", "Greetings", options);

                                                  Assert.That(doc.GetText().Trim(), Is.EqualTo(ignoreTextInsideFields
                                                          ? "Greetings world!\r\u0013QUOTE\u0014Hello again!\u0015"
                                                          : "Greetings world!\r\u0013QUOTE\u0014Greetings again!\u0015"));

Remarks

This option affects whole field (all nodes between Aspose.Words.NodeType.FieldStart and Aspose.Words.NodeType.FieldEnd).

To ignore only field codes, please use corresponding option Aspose.Words.Replacing.FindReplaceOptions.IgnoreFieldCodes.

IgnoreFootnotes

Gets or sets a boolean value indicating either to ignore footnotes. The default value is false.

public bool IgnoreFootnotes { get; set; }

Property Value

bool

Examples

Shows how to ignore footnotes during a find-and-replace operation.

Document doc = new Document();
                                                                             DocumentBuilder builder = new DocumentBuilder(doc);

                                                                             builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

                                                                             builder.InsertParagraph();

                                                                             builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

                                                                             // Set the "IgnoreFootnotes" flag to "true" to get the find-and-replace
                                                                             // operation to ignore text inside footnotes.
                                                                             // Set the "IgnoreFootnotes" flag to "false" to get the find-and-replace
                                                                             // operation to also search for text inside footnotes.
                                                                             FindReplaceOptions options = new FindReplaceOptions { IgnoreFootnotes = isIgnoreFootnotes };
                                                                             doc.Range.Replace("Lorem ipsum", "Replaced Lorem ipsum", options);

IgnoreInserted

Gets or sets a boolean value indicating either to ignore text inside insert revisions. The default value is false.

public bool IgnoreInserted { get; set; }

Property Value

bool

Examples

Shows how to include or ignore text inside insert revisions during a find-and-replace operation.

Document doc = new Document();
                                                                                                           DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                           builder.Writeln("Hello world!");

                                                                                                           // Start tracking revisions and insert a paragraph. That paragraph will be an insert revision.
                                                                                                           doc.StartTrackRevisions("John Doe", DateTime.Now);
                                                                                                           builder.Writeln("Hello again!");
                                                                                                           doc.StopTrackRevisions();

                                                                                                           Assert.That(doc.FirstSection.Body.Paragraphs[1].IsInsertRevision, Is.True);

                                                                                                           // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                                           FindReplaceOptions options = new FindReplaceOptions();

                                                                                                           // Set the "IgnoreInserted" flag to "true" to get the find-and-replace
                                                                                                           // operation to ignore paragraphs that are insert revisions.
                                                                                                           // Set the "IgnoreInserted" flag to "false" to get the find-and-replace
                                                                                                           // operation to also search for text inside insert revisions.
                                                                                                           options.IgnoreInserted = ignoreTextInsideInsertRevisions;

                                                                                                           doc.Range.Replace("Hello", "Greetings", options);

                                                                                                           Assert.That(doc.GetText().Trim(), Is.EqualTo(ignoreTextInsideInsertRevisions
                                                                                                                   ? "Greetings world!\rHello again!"
                                                                                                                   : "Greetings world!\rGreetings again!"));

IgnoreOfficeMath

Gets or sets a boolean value indicating either to ignore text inside OfficeMath/>. The default value is true.

public bool IgnoreOfficeMath { get; set; }

Property Value

bool

Examples

Shows how to find and replace text within OfficeMath.

Document doc = new Document(MyDir + "Office math.docx");

                                                                Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("i+b-c≥iM+bM-cM"));

                                                                FindReplaceOptions options = new FindReplaceOptions();
                                                                options.IgnoreOfficeMath = isIgnoreOfficeMath;
                                                                doc.Range.Replace("b", "x", options);

                                                                if (isIgnoreOfficeMath)
                                                                    Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("i+b-c≥iM+bM-cM"));
                                                                else
                                                                    Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("i+x-c≥iM+xM-cM"));

IgnoreShapes

Gets or sets a boolean value indicating either to ignore shapes within a text.

The default value is false.

public bool IgnoreShapes { get; set; }

Property Value

bool

Examples

Shows how to ignore shapes while replacing text.

Document doc = new Document();
                                                           DocumentBuilder builder = new DocumentBuilder(doc);

                                                           builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
                                                           builder.InsertShape(ShapeType.Balloon, 200, 200);
                                                           builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

                                                           FindReplaceOptions findReplaceOptions = new FindReplaceOptions() { IgnoreShapes = true };
                                                           builder.Document.Range.Replace("Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                                                               "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", findReplaceOptions);
                                                           Assert.That(builder.Document.GetText().Trim(), Is.EqualTo("Lorem ipsum dolor sit amet, consectetur adipiscing elit."));

IgnoreStructuredDocumentTags

Gets or sets a boolean value indicating either to ignore content of Aspose.Words.Markup.StructuredDocumentTag. The default value is false.

public bool IgnoreStructuredDocumentTags { get; set; }

Property Value

bool

Examples

Shows how to ignore content of tags from replacement.

Document doc = new Document(MyDir + "Structured document tags.docx");

                                                                // This paragraph contains SDT.
                                                                Paragraph p = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 2, true);
                                                                string textToSearch = p.ToString(SaveFormat.Text).Trim();

                                                                FindReplaceOptions options = new FindReplaceOptions() { IgnoreStructuredDocumentTags = true };
                                                                doc.Range.Replace(textToSearch, "replacement", options);

                                                                doc.Save(ArtifactsDir + "StructuredDocumentTag.IgnoreStructuredDocumentTags.docx");

Remarks

When this option is set to true, the content of Aspose.Words.Markup.StructuredDocumentTag will be treated as a simple text.

Otherwise, Aspose.Words.Markup.StructuredDocumentTag will be processed as standalone Story and replacing pattern will be searched separately for each Aspose.Words.Markup.StructuredDocumentTag, so that if pattern crosses a Aspose.Words.Markup.StructuredDocumentTag, then replacement will not be performed for such pattern.

LegacyMode

Gets or sets a boolean value indicating that old find/replace algorithm is used.

public bool LegacyMode { get; set; }

Property Value

bool

Examples

Shows how to recognize and use substitutions within replacement patterns.

Document doc = new Document();
                                                                                    DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                    builder.Write("Jason gave money to Paul.");

                                                                                    Regex regex = new Regex(@"([A-z]+) gave money to ([A-z]+)");

                                                                                    FindReplaceOptions options = new FindReplaceOptions();
                                                                                    options.UseSubstitutions = true;

                                                                                    // Using legacy mode does not support many advanced features, so we need to set it to 'false'.
                                                                                    options.LegacyMode = false;

                                                                                    doc.Range.Replace(regex, @"$2 took money from $1", options);

                                                                                    Assert.That("Paul took money from Jason.\f", Is.EqualTo(doc.GetText()));

Remarks

Use this flag if you need exactly the same behavior as before advanced find/replace feature was introduced. Note that old algorithm does not support advanced features such as replace with breaks, apply formatting and so on.

MatchCase

True indicates case-sensitive comparison, false indicates case-insensitive comparison.

public bool MatchCase { get; set; }

Property Value

bool

Examples

Shows how to toggle case sensitivity when performing a find-and-replace operation.

Document doc = new Document();
                                                                                             DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                             builder.Writeln("Ruby bought a ruby necklace.");

                                                                                             // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                             FindReplaceOptions options = new FindReplaceOptions();

                                                                                             // Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
                                                                                             // Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
                                                                                             options.MatchCase = matchCase;

                                                                                             doc.Range.Replace("Ruby", "Jade", options);

                                                                                             Assert.That(doc.GetText().Trim(), Is.EqualTo(matchCase ? "Jade bought a ruby necklace." : "Jade bought a Jade necklace."));

ReplacementFormat

Specifies format of the replacement. Default is Aspose.Words.Replacing.ReplacementFormat.Text.

public ReplacementFormat ReplacementFormat { get; set; }

Property Value

ReplacementFormat

Remarks

Has effect only when using in Aspose.Words.LowCode.Replacer

ReplacingCallback

The user-defined method which is called before every replace occurrence.

public IReplacingCallback ReplacingCallback { get; set; }

Property Value

IReplacingCallback

Examples

Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.

public void ReplaceWithCallback()
                                                                                                                                          {
                                                                                                                                              Document doc = new Document();
                                                                                                                                              DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                                                              builder.Writeln("Our new location in New York City is opening tomorrow. " +
                                                                                                                                                              "Hope to see all our NYC-based customers at the opening!");

                                                                                                                                              // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                                                                              FindReplaceOptions options = new FindReplaceOptions();

                                                                                                                                              // Set a callback that tracks any replacements that the "Replace" method will make.
                                                                                                                                              TextFindAndReplacementLogger logger = new TextFindAndReplacementLogger();
                                                                                                                                              options.ReplacingCallback = logger;

                                                                                                                                              doc.Range.Replace(new Regex("New York City|NYC"), "Washington", options);

                                                                                                                                              Assert.That(doc.GetText().Trim(), Is.EqualTo("Our new location in (Old value:\"New York City\") Washington is opening tomorrow. " +
                                                                                                                                                              "Hope to see all our (Old value:\"NYC\") Washington-based customers at the opening!"));

                                                                                                                                              Assert.That(logger.GetLog().Trim(), Is.EqualTo("\"New York City\" converted to \"Washington\" 20 characters into a Run node.\r\n" +
                                                                                                                                                              "\"NYC\" converted to \"Washington\" 42 characters into a Run node."));
                                                                                                                                          }

                                                                                                                                          /// <summary>
                                                                                                                                          /// Maintains a log of every text replacement done by a find-and-replace operation
                                                                                                                                          /// and notes the original matched text's value.
                                                                                                                                          /// </summary>
                                                                                                                                          private class TextFindAndReplacementLogger : IReplacingCallback
                                                                                                                                          {
                                                                                                                                              ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
                                                                                                                                              {
                                                                                                                                                  mLog.AppendLine($"\"{args.Match.Value}\" converted to \"{args.Replacement}\" " +
                                                                                                                                                                  $"{args.MatchOffset} characters into a {args.MatchNode.NodeType} node.");

                                                                                                                                                  args.Replacement = $"(Old value:\"{args.Match.Value}\") {args.Replacement}";
                                                                                                                                                  return ReplaceAction.Replace;
                                                                                                                                              }

                                                                                                                                              public string GetLog()
                                                                                                                                              {
                                                                                                                                                  return mLog.ToString();
                                                                                                                                              }

                                                                                                                                              private readonly StringBuilder mLog = new StringBuilder();
                                                                                                                                          }

Shows how to apply a different font to new content via FindReplaceOptions.

public void ConvertNumbersToHexadecimal()
                                                                                     {
                                                                                         Document doc = new Document();
                                                                                         DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                         builder.Font.Name = "Arial";
                                                                                         builder.Writeln("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\n" +
                                                                                                         "123, 456, 789 and 17379.");

                                                                                         // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                         FindReplaceOptions options = new FindReplaceOptions();

                                                                                         // Set the "HighlightColor" property to a background color that we want to apply to the operation's resulting text.
                                                                                         options.ApplyFont.HighlightColor = Color.LightGray;

                                                                                         NumberHexer numberHexer = new NumberHexer();
                                                                                         options.ReplacingCallback = numberHexer;

                                                                                         int replacementCount = doc.Range.Replace(new Regex("[0-9]+"), "", options);

                                                                                         Console.WriteLine(numberHexer.GetLog());

                                                                                         Assert.That(replacementCount, Is.EqualTo(4));
                                                                                         Assert.That(doc.GetText().Trim(), Is.EqualTo("Numbers that the find-and-replace operation will convert to hexadecimal and highlight:\r" +
                                                                                                         "0x7B, 0x1C8, 0x315 and 0x43E3."));
                                                                                         Assert.That(doc.GetChildNodes(NodeType.Run, true).OfType<Run>()
                                                                                                 .Count(r => r.Font.HighlightColor.ToArgb() == Color.LightGray.ToArgb()), Is.EqualTo(4));
                                                                                     }

                                                                                     /// <summary>
                                                                                     /// Replaces numeric find-and-replacement matches with their hexadecimal equivalents.
                                                                                     /// Maintains a log of every replacement.
                                                                                     /// </summary>
                                                                                     private class NumberHexer : IReplacingCallback
                                                                                     {
                                                                                         public ReplaceAction Replacing(ReplacingArgs args)
                                                                                         {
                                                                                             mCurrentReplacementNumber++;

                                                                                             int number = Convert.ToInt32(args.Match.Value);

                                                                                             args.Replacement = $"0x{number:X}";

                                                                                             mLog.AppendLine($"Match #{mCurrentReplacementNumber}");
                                                                                             mLog.AppendLine($"\tOriginal value:\t{args.Match.Value}");
                                                                                             mLog.AppendLine($"\tReplacement:\t{args.Replacement}");
                                                                                             mLog.AppendLine($"\tOffset in parent {args.MatchNode.NodeType} node:\t{args.MatchOffset}");

                                                                                             mLog.AppendLine(string.IsNullOrEmpty(args.GroupName)
                                                                                                 ? $"\tGroup index:\t{args.GroupIndex}"
                                                                                                 : $"\tGroup name:\t{args.GroupName}");

                                                                                             return ReplaceAction.Replace;
                                                                                         }

                                                                                         public string GetLog()
                                                                                         {
                                                                                             return mLog.ToString();
                                                                                         }

                                                                                         private int mCurrentReplacementNumber;
                                                                                         private readonly StringBuilder mLog = new StringBuilder();
                                                                                     }

SmartParagraphBreakReplacement

Gets or sets a boolean value indicating either it is allowed to replace paragraph break when there is no next sibling paragraph.

The default value is false.

public bool SmartParagraphBreakReplacement { get; set; }

Property Value

bool

Examples

Shows how to remove paragraph from a table cell with a nested table.

Document doc = new Document();
                                                                               DocumentBuilder builder = new DocumentBuilder(doc);

                                                                               // Create table with paragraph and inner table in first cell.
                                                                               builder.StartTable();
                                                                               builder.InsertCell();
                                                                               builder.Write("TEXT1");
                                                                               builder.StartTable();
                                                                               builder.InsertCell();
                                                                               builder.EndTable();
                                                                               builder.EndTable();
                                                                               builder.Writeln();

                                                                               FindReplaceOptions options = new FindReplaceOptions();
                                                                               // When the following option is set to 'true', Aspose.Words will remove paragraph's text
                                                                               // completely with its paragraph mark. Otherwise, Aspose.Words will mimic Word and remove
                                                                               // only paragraph's text and leaves the paragraph mark intact (when a table follows the text).
                                                                               options.SmartParagraphBreakReplacement = isSmartParagraphBreakReplacement;
                                                                               doc.Range.Replace(new Regex(@"TEXT1&p"), "", options);

                                                                               doc.Save(ArtifactsDir + "Table.RemoveParagraphTextAndMark.docx");

Remarks

This option allows to replace paragraph break when there is no next sibling paragraph to which all child nodes can be moved, by finding any (not necessarily sibling) next paragraph after the paragraph being replaced.

UseLegacyOrder

True indicates that a text search is performed sequentially from top to bottom considering the text boxes. Default value is false.

public bool UseLegacyOrder { get; set; }

Property Value

bool

Examples

Shows how to change the searching order of nodes when performing a find-and-replace text operation.

public void UseLegacyOrder(bool useLegacyOrder)
                                                                                                              {
                                                                                                                  Document doc = new Document();
                                                                                                                  DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                                  // Insert three runs which we can search for using a regex pattern.
                                                                                                                  // Place one of those runs inside a text box.
                                                                                                                  builder.Writeln("[tag 1]");
                                                                                                                  Shape textBox = builder.InsertShape(ShapeType.TextBox, 100, 50);
                                                                                                                  builder.Writeln("[tag 2]");
                                                                                                                  builder.MoveTo(textBox.FirstParagraph);
                                                                                                                  builder.Write("[tag 3]");

                                                                                                                  // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                                                                                  FindReplaceOptions options = new FindReplaceOptions();

                                                                                                                  // Assign a custom callback to the "ReplacingCallback" property.
                                                                                                                  TextReplacementTracker callback = new TextReplacementTracker();
                                                                                                                  options.ReplacingCallback = callback;

                                                                                                                  // If we set the "UseLegacyOrder" property to "true", the
                                                                                                                  // find-and-replace operation will go through all the runs outside of a text box
                                                                                                                  // before going through the ones inside a text box.
                                                                                                                  // If we set the "UseLegacyOrder" property to "false", the
                                                                                                                  // find-and-replace operation will go over all the runs in a range in sequential order.
                                                                                                                  options.UseLegacyOrder = useLegacyOrder;

                                                                                                                  doc.Range.Replace(new Regex(@"\[tag \d*\]"), "", options);

                                                                                                                  List<string> expected;
                                                                                                                  if (useLegacyOrder)
                                                                                                                      expected = new List<string> { "[tag 1]", "[tag 3]", "[tag 2]" };
                                                                                                                  else
                                                                                                                      expected = new List<string> { "[tag 1]", "[tag 2]", "[tag 3]" };
                                                                                                                  Assert.That(callback.Matches, Is.EqualTo(expected));

                                                                                                              }

                                                                                                              /// <summary>
                                                                                                              /// Records the order of all matches that occur during a find-and-replace operation.
                                                                                                              /// </summary>
                                                                                                              private class TextReplacementTracker : IReplacingCallback
                                                                                                              {
                                                                                                                  ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
                                                                                                                  {
                                                                                                                      Matches.Add(e.Match.Value);
                                                                                                                      return ReplaceAction.Replace;
                                                                                                                  }

                                                                                                                  public List<string> Matches { get; } = new List<string>();
                                                                                                              }

UseSubstitutions

Gets or sets a boolean value indicating whether to recognize and use substitutions within replacement patterns. The default value is false.

public bool UseSubstitutions { get; set; }

Property Value

bool

Examples

Shows how to recognize and use substitutions within replacement patterns.

Document doc = new Document();
                                                                                    DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                    builder.Write("Jason gave money to Paul.");

                                                                                    Regex regex = new Regex(@"([A-z]+) gave money to ([A-z]+)");

                                                                                    FindReplaceOptions options = new FindReplaceOptions();
                                                                                    options.UseSubstitutions = true;

                                                                                    // Using legacy mode does not support many advanced features, so we need to set it to 'false'.
                                                                                    options.LegacyMode = false;

                                                                                    doc.Range.Replace(regex, @"$2 took money from $1", options);

                                                                                    Assert.That("Paul took money from Jason.\f", Is.EqualTo(doc.GetText()));

Shows how to replace the text with substitutions.

Document doc = new Document();
                                                            DocumentBuilder builder = new DocumentBuilder(doc);

                                                            builder.Writeln("John sold a car to Paul.");
                                                            builder.Writeln("Jane sold a house to Joe.");

                                                            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
                                                            FindReplaceOptions options = new FindReplaceOptions();

                                                            // Set the "UseSubstitutions" property to "true" to get
                                                            // the find-and-replace operation to recognize substitution elements.
                                                            // Set the "UseSubstitutions" property to "false" to ignore substitution elements.
                                                            options.UseSubstitutions = useSubstitutions;

                                                            Regex regex = new Regex(@"([A-z]+) sold a ([A-z]+) to ([A-z]+)");
                                                            doc.Range.Replace(regex, @"$3 bought a $2 from $1", options);

                                                            Assert.That(doc.GetText().Trim(), Is.EqualTo(useSubstitutions
                                                                    ? "Paul bought a car from John.\rJoe bought a house from Jane."
                                                                    : "$3 bought a $2 from $1.\r$3 bought a $2 from $1."));

Remarks

For the details on substitution elements please refer to: https://docs.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions .

 English