Regular expressions, often abbreviated as regex, are powerful tools for matching and manipulating strings based on patterns. In C#, regex is implemented through the System.Text.RegularExpressions namespace. One of the most common operations performed with regex is replacement, which involves substituting matched patterns with new text. This article will delve into the world of C# regex replacement, providing you with a solid understanding of how to use it effectively.
Understanding Regex Replacement in C#
At its core, regex replacement in C# involves using the Regex.Replace method, which takes two main parameters: the input string and the replacement pattern. The method returns a new string where all matches of the regex pattern have been replaced with the specified replacement text.
Here's a simple example to get you started:

```csharp using System; using System.Text.RegularExpressions; public class Program { public static void Main() { string input = "Hello, World! Hello, Regex!"; string pattern = @"\bHello\b"; string replacement = "Hi"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result); // Output: Hi, World! Hi, Regex! } } ```
Regex Patterns and Replacement Text
The regex pattern and replacement text can be as simple or as complex as you need them to be. Here are a few examples:
- Simple text replacement: Replace all occurrences of "world" with "universe".
- Regex pattern replacement: Replace all email addresses with "[REDACTED]".
- Regex with capture groups: Replace the date in "Today is 2022-01-01" with the current date.
Using Regex Options
C# regex provides several options that can be used to modify the behavior of the Regex.Replace method. These options are specified as a bitwise combination of the RegexOptions enum. Some commonly used options include:
| Option | Description |
|---|---|
IgnoreCase |
Makes the regex pattern case-insensitive. |
Multiline |
Changes the behavior of ^ and $ to match the beginning and end of any line (not just the beginning and end of the string). |
Regex Replacement with Capture Groups
Capture groups allow you to extract parts of the matched text and use them in the replacement text. To use capture groups, enclose the pattern you want to capture in parentheses. The captured text can then be referenced in the replacement text using a backreference (e.g., \\1, \\2, etc.).

Here's an example that replaces the date in a string with the current date, using capture groups to extract the day, month, and year:
```csharp string input = "Today is 2022-01-01"; string pattern = @"(\d{4})-(\d{2})-(\d{2})"; string replacement = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}"; string result = Regex.Replace(input, pattern, replacement, RegexOptions.IgnoreCase); Console.WriteLine(result); // Output: Today is 2023-02-15 (assuming the current date is February 15, 2023) ```
Regex Replacement with MatchEvaluator
In some cases, you may need more control over the replacement process than the simple Regex.Replace method provides. For these situations, you can use the Regex.Replace overload that takes a MatchEvaluator delegate. This delegate is called for each match, allowing you to perform custom replacement logic.
Here's an example that replaces all email addresses with "[REDACTED]", but only if the email domain is "example.com":

```csharp string input = "Send your feedback to john@example.com or jane@other.com."; string pattern = @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"; string result = Regex.Replace(input, pattern, match => { string email = match.Value; if (email.EndsWith("@example.com")) { return "[REDACTED]"; } else { return email; } }); Console.WriteLine(result); // Output: Send your feedback to [REDACTED] or jane@other.com. ```
Best Practices for Regex Replacement
Here are some best practices to keep in mind when working with regex replacement in C#:
- Test your regex patterns thoroughly to ensure they match the desired input.
- Use capture groups sparingly, as they can make your regex patterns more complex and difficult to understand.
- Consider using the
Regex.Escapemethod to escape special characters in your replacement text, to avoid unexpected behavior. - Be mindful of performance, as regex operations can be resource-intensive. Try to minimize the number of regex calls and use efficient patterns.
Regex replacement is a powerful tool that can greatly simplify tasks such as data manipulation, text processing, and string formatting. By understanding and mastering the techniques outlined in this article, you'll be well-equipped to tackle a wide range of string manipulation challenges in C#.





















