Regular Expressions in C# Language
Regular expressions, often abbreviated as regex or regexp, are a powerful tool for text processing and pattern matching in various programming languages. In
Regular expressions, often abbreviated as regex or regexp, are a powerful tool for text processing and pattern matching in various programming languages. In
System.Text.RegularExpressions
namespace, and they provide a versatile way to search, match, and manipulate text data. This post will introduce you to the basics of using regular expressions in C# with practical examples.
Before we dive into examples, make sure you have the System.Text.RegularExpressions
namespace included in your project by adding the following line at the top of your C# file:
using System.Text.RegularExpressions;
In C#, you create a regular expression by instantiating the Regex
class, which allows you to define a pattern to search for in a string. Here’s an example of creating a simple regex to match an email address:
string pattern = @"[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+";
Regex regex = new Regex(pattern);
In this example, we’ve defined a regex pattern that matches a typical email address.
To search for and extract text that matches your regular expression, you can use the Match
method. Here’s how you would use it with the email regex:
string text = "Contact us at support@example.com or info@example.org";
MatchCollection matches = regex.Matches(text);
foreach (Match match in matches)
{
Console.WriteLine("Match found: " + match.Value);
}
In this code, the Matches
method finds all matches in the input string, and we iterate through the MatchCollection
to print out the matched email addresses.
Regular expressions allow you to define groups within your patterns. You can use these groups to extract specific parts of the matched text. Let’s modify our email regex example to capture the username and domain separately:
string pattern = @"(?<username>[\w-]+)(@)(?<domain>[\w-]+(\.[\w-]+)+)";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(text);
foreach (Match match in matches)
{
string username = match.Groups["username"].Value;
string domain = match.Groups["domain"].Value;
Console.WriteLine("Username: " + username);
Console.WriteLine("Domain: " + domain);
}
In this code, we use named groups to extract the username and domain from each email address.
Regular expressions in C# are also useful for text replacement. You can use the Regex.Replace
method to replace text that matches a pattern. Here’s an example:
string text = "My phone number is (123) 456-7890.";
string pattern = @"\(\d{3}\) \d{3}-\d{4}";
string replacement = "###-###-####";
string result = Regex.Replace(text, pattern, replacement);
Console.WriteLine("Modified text: " + result);
In this example, we replace a phone number with a generic format (###-###-####).
Subscribe to get the latest posts sent to your email.