0
0
CsharpHow-ToBeginner · 3 min read

How to Use Regex.Replace in C# for Text Replacement

Use Regex.Replace in C# to find text matching a pattern and replace it with a new string. It takes the input text, a regular expression pattern, and a replacement string, returning the modified text.
📐

Syntax

The Regex.Replace method has this basic syntax:

  • input: The original string where you want to replace text.
  • pattern: The regular expression pattern to find matches.
  • replacement: The string to replace each match with.

It returns a new string with replacements applied.

csharp
string result = Regex.Replace(input, pattern, replacement);
💻

Example

This example shows how to replace all digits in a string with the '#' character using Regex.Replace.

csharp
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "My phone number is 123-456-7890.";
        string pattern = "\\d"; // Matches any digit
        string replacement = "#";

        string result = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(result);
    }
}
Output
My phone number is ###-###-####.
⚠️

Common Pitfalls

Common mistakes when using Regex.Replace include:

  • Forgetting to escape special characters in the pattern (e.g., use \\d for digits, not \d in strings).
  • Using the wrong pattern that matches unintended text.
  • Not importing System.Text.RegularExpressions namespace.
  • Assuming Regex.Replace changes the original string (strings are immutable; it returns a new string).
csharp
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Price: $100";
        // Wrong pattern: missing escape for $ (special char)
        string wrongPattern = "$\d+";
        string replacement = "USD";

        // This will throw an error or behave unexpectedly
        // string wrongResult = Regex.Replace(input, wrongPattern, replacement);

        // Correct pattern with escape
        string correctPattern = "\$\d+";
        string correctResult = Regex.Replace(input, correctPattern, replacement);
        Console.WriteLine(correctResult); // Output: Price: USD
    }
}
Output
Price: USD
📊

Quick Reference

Tips for using Regex.Replace effectively:

  • Always escape special regex characters in patterns.
  • Use verbatim strings @"pattern" to reduce escaping.
  • Remember it returns a new string; original is unchanged.
  • You can use RegexOptions overloads for case-insensitive or multiline replacements.

Key Takeaways

Regex.Replace finds text matching a pattern and returns a new string with replacements.
Escape special characters in patterns to avoid errors or unexpected matches.
Use verbatim strings (@"pattern") to simplify regex patterns in C#.
Regex.Replace does not change the original string; it returns a modified copy.
You can customize behavior with RegexOptions for case or culture sensitivity.