Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.