One of the popular uses cases related to the documents is finding and replacing the text programmatically. There could be multiple cases when you need to replace a word or phrase in the document. For example, you want to censor the content before sharing the document publically or you want to hide/remove all the email IDs or Social Security Numbers provided in the document before putting it online.
So in this article, I am going to target this use case and will show you how you could easily find and replace your desired text in documents programmatically using C#. For this, I will use GroupDocs.Redaction for .NET API which provides multiple ways to hide or replace text in the popular formats of MS Word, Excel, PowerPoint, and PDF documents.
So you don’t need MS Office, PDF editor or any other third party software in this scenario. Let’s now begin and have a look at different approaches to deal with finding and replacing text in the documents. The following is the screenshot of a Word document that I have used in the examples for demonstration. The same methods will work for other document formats I have mentioned above without any change in the code.
Find and Replace a Word or Phrase in C#
This is how you can replace a single word or phrase in the document.
Find and Replace Case-Sensitive Word or Phrase using C#
In case you want to replace text considering its case sensitivity, use the following code.
Find and Replace Text using Regular Expressions (RegEx) in C#
If you need to replace the text occurrences that are following a particular pattern, for example SS#, you can do it using the regular expressions.
Find and Replace the Text with Colored Box in C#
You can also replace your desired text with a colored box.
For more details on the working and features of GroupDocs.Redaction for .NET, have a look at the documentation of the API.