Find and Replace Text in Text / HTML Files

Introduction

Here is the simple and quick way to replace a text in a HTML or TEXT file.

using System;
using System.IO;
using System.Text.RegularExpressions;

public void ReplaceInFile(string filePath, string replaceText, string findText)
{
    try
    {
        // Read the complete file and replace the text
        using (StreamReader reader = new StreamReader(filePath))
        {
            string content = reader.ReadToEnd();
            content = Regex.Replace(content, findText, replaceText);
            
            // Write the content back to the file
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.Write(content);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred: " + ex.Message);
        // Handle the exception as needed (logging, etc.)
    }
}

Regex is a class that represents the .NET framework regular expression engine. It plays a vital role in quickly parsing a large amount of text to find specific patterns; to extract, edit, replace or delete text substrings

How to use the Regular Expression Syntax?

To implement the regular expression, you should follow a certain pattern that you want to identify in your text stream. At the next step you can instantiate the Regex class and do your operations such as replacing text, editing text, removing white spaces, & etc.

Following table has the pattern and the description for it. Hope this could help you to implement your own logic.

Pattern Description
^ Start at the beginning of the string.
\s* Match zero or more white-space characters.
[\+-]? Match zero or one occurrence of either the positive sign or the negative sign.
\s? Match zero or one white-space character.
\$? Match zero or one occurrence of the dollar sign.
\s? Match zero or one white-space character.
\d* Match zero or more decimal digits.
\.? Match zero or one decimal point symbol.
\d{2}? Match two decimal digits zero or one time.
(\d*\.?\d{2}?){1} Match the pattern of integral and fractional digits separated by a decimal point symbol at least one time.
$ Match the end of the string.


Recommended Free Ebook
Similar Articles