C# Regex Examples

Regular expressions (regex or regexp) in C# are powerful tools for pattern matching and text manipulation. They allow you to define search patterns that can match and extract specific substrings within a larger text.

Using the Regex Class in C#

C# provides the System.Text.RegularExpressions.Regex class to work with regular expressions. You need to include the using System.Text.RegularExpressions; namespace.

Here is an example of a regular expression in C#:

var regex = new Regex("[a-zA-Z0-9]+");

This regular expression matches any string that contains one or more alphanumeric characters.

Search for a match in a string

Here is an example of how to use the regular expression to search for a match in a string:

using System; using System.Text.RegularExpressions; class Program { static void Main() { var stringToSearch = "This is a test string."; var pattern = @"test"; // Replace this with your desired regex pattern var regex = new Regex(pattern); var match = regex.Match(stringToSearch); if (match.Success) { Console.WriteLine("Found a match!"); } else { Console.WriteLine("No match found."); } } }
//Output: Found a match!

Simple Pattern Matching

You can use regex to find simple patterns in a string. For example, let's find all email addresses in a given text:

using System; using System.Text.RegularExpressions; public class HelloWorld { public static void Main(string[] args) { string text = "Email ID at support@example.com or sales@company.com."; string pattern = @"\b\w+@\w+\.\w+\b"; // Matches email addresses MatchCollection matches = Regex.Matches(text, pattern); foreach (Match match in matches) { Console.WriteLine(match.Value); } } }
//Output: support@example.com sales@company.com

In this example, the pattern \b\w+@\w+\.\w+\b matches words that look like email addresses.

  1. \b indicates word boundaries
  2. \w+ matches one or more word characters
  3. @ matches the literal "@" symbol
  4. \. matches the dot in the domain

The Matches method finds all matches in the text and stores them in a MatchCollection.

Capturing Groups

You can use capturing groups to extract specific parts of a match. Let's extract the username and domain from email addresses:

using System; using System.Text.RegularExpressions; class Program { static void Main() { string text = "Contact us at support@example.com or sales@company.com."; string pattern = @"(\w+)@(\w+\.\w+)\b"; // Capturing groups for username and domain MatchCollection matches = Regex.Matches(text, pattern); foreach (Match match in matches) { string username = match.Groups[1].Value; string domain = match.Groups[2].Value; Console.WriteLine($"Username: {username}, Domain: {domain}"); } } }
//Output: Username: support, Domain: example.com Username: sales, Domain: company.com

In this example, pattern @"(\w+)@(\w+\.\w+)\b"; capturing groups for username and domain

  1. (\w+) captures the username
  2. (\w+\.\w+) captures the domain

Replace with Regex

You can also use regex to perform string replacements based on patterns. For example, let's replace all occurrences of "apple" with "orange" in a text:

using System; using System.Text.RegularExpressions; class Program { static void Main() { string text = "I have an apple, and she has an apple too."; string pattern = "apple"; string replacedText = Regex.Replace(text, pattern, "orange"); Console.WriteLine(replacedText); } }
//Output: I have an orange, and she has an orange too.

In the above example, we use the Replace method to substitute all occurrences of "apple" with "orange" in the text.

Validation with Regex

Regular expressions are commonly used for input validation. For instance, you can validate that a string follows a specific format, like checking if a string is a valid date:

using System; using System.Text.RegularExpressions; class Program { static void Main() { string date = "2023-09-22"; string pattern = @"^ \d{4}-\d{2}-\d{2}$"; // Matches YYYY-MM-DD format bool isValidDate = Regex.IsMatch(date, pattern); Console.WriteLine($"Is valid date: {isValidDate}"); } }
//Output: Is valid date: True

Here, IsMatch checks if the date string matches the specified pattern for a valid date.

Extract data from a string

Regular expressions can also be used to extract data from a string

using System; using System.Text.RegularExpressions; class Program { static void Main() { var regex = new Regex(@"(\w+)@(\w+)\.(\w+)"); var match = regex.Match("jimmy.wales@example.com"); if (match.Success) { var username = match.Groups[1].Value; var domain = match.Groups[2].Value; var extension = match.Groups[3].Value; Console.WriteLine($"Username: {username}"); Console.WriteLine($"Domain: {domain}"); Console.WriteLine($"Extension: {extension}"); } else { Console.WriteLine("No match found."); } } }
//Output: Username: wales Domain: example Extension: com

Conclusion

Regular expressions in C# (regex) are powerful tools for pattern matching and text manipulation. They enable you to define and search for specific patterns within strings, making them invaluable for tasks like validation, data extraction, and text processing. By utilizing the System.Text.RegularExpressions namespace, developers can create versatile regex patterns and use them effectively in C# applications.