An Introduction to Regular Expressions in .NET

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:

  • Matching: Check if a string fits a pattern.
  • Searching: Find patterns within strings.
  • Replacing: Substitute matched patterns.
  • Splitting: Divide strings based on patterns.

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

  • Verbatim Strings: Use @ before strings to simplify patterns (e.g., @"\d+").
  • Precompile Patterns: For frequent use, compile regex with RegexOptions.Compiled for better performance.
  • Testing Patterns: Use online tools like Regex101 to test and refine your patterns.
  • Handle Exceptions: Please be careful RegexMatchTimeoutException to avoid performance issues.


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.

要查看或添加评论,请登录

Andrei I.的更多文章

社区洞察

其他会员也浏览了