An Introduction to Regular Expressions in .NET
Regular expressions (regex) are powerful tools for pattern matching and text manipulation. In .NET, the System.Text.RegularExpressions namespace provides classes and methods to work with regex efficiently.
The Regex Class
The Regex class is central to regex operations in .NET and offers methods for:
Include the namespace in your code:
using System.Text.RegularExpressions;
Basic Examples
Matching a Pattern
string pattern = @"^\d{3}-\d{2}-\d{4}$"; // Social Security Number format
string input = "123-45-6789";
bool isMatch = Regex.IsMatch(input, pattern);
// isMatch is True
Extracting Matches
string pattern = @"\b\w+@\w+\.\w+\b"; // Simple email pattern
string input = "Email us at [email protected] or [email protected].";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
// Outputs:
// [email protected]
// [email protected]
Replacing Text
string pattern = @"\d";
string replacement = "#";
string input = "User123";
string result = Regex.Replace(input, pattern, replacement);
// result is "User###"
Splitting a String
string pattern = @",\s*";
string input = "apple, banana, cherry";
string[] fruits = Regex.Split(input, pattern);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// Outputs:
// apple
// banana
// cherry
Tips and Best Practices
Regular expressions in .NET simplify complex text processing tasks. By mastering the Regex class and common patterns, you can enhance your applications with robust string-handling capabilities.