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/dafaf8f41192a14524e1e88cc2ce4742 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/dafaf8f41192a14524e1e88cc2ce4742 to your computer and use it in GitHub Desktop.
Aspose.Words for .NET - Find and Replace Text
// Load a Word docx document
Document doc = new Document("document.docx");
FindReplaceOptions options = new FindReplaceOptions();
options.FindWholeWordsOnly = true;
// Set regular expression for email IDs
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])?");
// Find and replace text in the document
doc.Range.Replace(EmailRegex, "[replaced]", options);
// Save the Word document
doc.Save("Find-And-Replace-Text-Using-Regex.docx");
// Load a Word docx document
Document doc = new Document("document.docx");
// Find and replace text in the document
doc.Range.Replace("sad", "[replaced]", new FindReplaceOptions(FindReplaceDirection.Forward));
// Save the Word document
doc.Save("Find-And-Replace-Text.docx");
// Load a Word docx document
Document doc = new Document("document.docx");
// Set options
FindReplaceOptions options = new FindReplaceOptions
{
MatchCase = false,
FindWholeWordsOnly = false
};
// Replace text with paragraph break
doc.Range.Replace("First paragraph ends.&pSecond paragraph starts.", "[replaced]", options);
// Save the Word document
doc.Save("Find-And-Replace-Text-Paragraph-Break.docx");
// Load a Word docx document
Document doc = new Document("document.docx");
FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = true;
// Find and replace text in the document
doc.Range.Replace(new Regex("[B|S|M]ad"), "[replaced]", options);
// Save the Word document
doc.Save("Find-And-Replace-Multiple-Words.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment