C#RegexIntermediate

Regex.Match() / Regex.Replace()

`Regex.Match()` finds the first occurrence of a regular expression pattern in an input string, while `Regex.Replace()` replaces all occurrences of a pattern with a specified replacement string.

Review the syntaxStudy the examplesOpen the coding app
Match Regex.Match(string input, string pattern)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

`Regex.Match()` finds the first occurrence of a regular expression pattern in an input string, while `Regex.Replace()` replaces all occurrences of a pattern with a specified replacement string.

The `System.Text.RegularExpressions.Regex` class in C# provides powerful capabilities for pattern-based string processing. `Regex.Match()` searches the input string for the first occurrence that matches the specified regular expression pattern and returns a `Match` object. This `Match` object contains information about the match, including its success, the matched value, and any captured groups. To find all matches, you would typically use `Regex.Matches()` which returns a `MatchCollection`. `Regex.Replace()`, on the other hand, finds all occurrences of the pattern within the input string and replaces them with the `replacement` string, returning a new string. The `replacement` string can include backreferences (`2`, etc.) to captured groups from the pattern. Regular expression operations can be computationally intensive, with time complexity varying significantly based on the complexity of the pattern and the length of the input string, often ranging from O(N) to exponential in worst-case "catastrophic backtracking" scenarios. Best practices include compiling frequently used regex patterns with `RegexOptions.Compiled` for performance, validating patterns to prevent `ArgumentException`, and being mindful of potential security vulnerabilities when using user-provided patterns. For simple string substitutions, `String.Replace()` is more efficient.

Quick reference

Syntax

Match Regex.Match(string input, string pattern)

Inputs

Parameters

inputstring · The string to search.
patternstring · The regular expression pattern to match.
replacementstring · The replacement string.

See it in practice

Examples

1

Basic Regex.Match to find a number

using System.Text.RegularExpressions;

string text = "The price is $12.99.";
Match match = Regex.Match(text, @"\d+\.\d+");
if (match.Success)
{
    Console.WriteLine($"Found price: {match.Value}");
}
Output:
Found price: 12.99

Uses `Regex.Match` to find the first occurrence of a decimal number in a string.

2

Extracting all numbers from a string

using System.Text.RegularExpressions;

string data = "Items: 10 apples, 5 oranges, 2 bananas.";
MatchCollection matches = Regex.Matches(data, @"\d+");
foreach (Match m in matches)
{
    Console.WriteLine($"Number: {m.Value}");
}
Output:
Number: 10 Number: 5 Number: 2

Uses `Regex.Matches` to find all sequences of digits (numbers) in a string.

3

Replacing email domains using Regex.Replace

using System.Text.RegularExpressions;

string emails = "user1@old.com, user2@legacy.org, user3@old.com";
string newEmails = Regex.Replace(emails, @"@(old\.com|legacy\.org)", "@new.net");
Console.WriteLine(newEmails);
Output:
user1@new.net, user2@new.net, user3@new.net

Replaces specific email domains with a new one using a regular expression.

Debug faster

Common Errors

1

ArgumentException

Cause: Providing an invalid regular expression pattern.

Fix: Carefully review the regex pattern for syntax errors. Use online regex testers to validate complex patterns.

using System.Text.RegularExpressions;

string text = "test";
try { Regex.Match(text, "["); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); }

Runtime support

Compatibility

.NETN/A.NET Framework 1.0+, .NET Core 1.0+

Source: Microsoft Learn

Common questions

Frequently Asked Questions

`Regex.Match()` finds the first occurrence of a regular expression pattern in an input string, while `Regex.Replace()` replaces all occurrences of a pattern with a specified replacement string.

input: The string to search. pattern: The regular expression pattern to match. replacement: The replacement string.

ArgumentException: Carefully review the regex pattern for syntax errors. Use online regex testers to validate complex patterns.