Skip to main content

Mastering Regular Expression. Part 3: Using Regular Expressions in C#

3.1 Introduction to Regex in C#

C# supports Regular Expressions via the powerful System.Text.RegularExpressions namespace. This includes:

  • Regex class for pattern matching
  • Match and capture support
  • Replace and split operations
  • Support for advanced features like lookarounds and named groups

3.2 Setting Up

Using the Namespace

using System.Text.RegularExpressions;

No external libraries are needed—everything is built into .NET.


3.3 Basic Pattern Matching

🔍 Example 1: Simple Match

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string pattern = @"hello";
        string input = "hello world";
        bool isMatch = Regex.IsMatch(input, pattern);
        Console.WriteLine(isMatch); // True
    }
}

3.4 Match Object and Groups

🔍 Example 2: Extracting Groups

string input = "My phone number is 123-456-7890.";
string pattern = @"(\d{3})-(\d{3})-(\d{4})";

Match match = Regex.Match(input, pattern);

if (match.Success) {
    Console.WriteLine("Full match: " + match.Value);       // 123-456-7890
    Console.WriteLine("Area code: " + match.Groups[1]);     // 123
    Console.WriteLine("Prefix: " + match.Groups[2]);        // 456
    Console.WriteLine("Line number: " + match.Groups[3]);   // 7890
}

3.5 Regex Replace

🔍 Example 3: Replacing Email Domain

string input = "Contact me at user@example.com";
string pattern = @"(@)\w+(\.com)";
string replacement = "@newdomain$2";

string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine(result); // Contact me at user@newdomain.com

3.6 Splitting Strings

🔍 Example 4: Split by Whitespace

string input = "one   two\tthree\nfour";
string pattern = @"\s+";

string[] words = Regex.Split(input, pattern);
foreach (string word in words) {
    Console.WriteLine(word);
}

3.7 RegexOptions in C#

You can pass options to customize behavior.

Option

Description

IgnoreCase

Case-insensitive matching

Multiline

^ and $ match line starts/ends

Singleline

. matches newline too

Compiled

Compiles regex for performance

ExplicitCapture

Only named/explicit groups are captured


🔍 Example 5: Case-Insensitive Match

3.8 Named Groups

string pattern = @"hello";
string input = "HELLO WORLD";

bool isMatch = Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
Console.WriteLine(isMatch); // True

🔍 Example 6: Capture with Names

3.9 Lookahead and Lookbehind

string pattern = @"(?<area>\d{3})-(?<prefix>\d{3})-(?<line>\d{4})";
string input = "Phone: 123-456-7890";

Match match = Regex.Match(input, pattern);

if (match.Success) {
    Console.WriteLine("Area: " + match.Groups["area"]);   // 123
    Console.WriteLine("Prefix: " + match.Groups["prefix"]); // 456
    Console.WriteLine("Line: " + match.Groups["line"]);   // 7890
}

C#’s regex engine supports lookarounds.

🔍 Example 7: Positive Lookahead

string input = "Price: 100USD and 200EUR";
string pattern = @"\d+(?=USD)";

Match match = Regex.Match(input, pattern);
Console.WriteLine(match.Value); // 100

Match only numbers followed by "USD":


🔍 Example 8: Negative Lookbehind

string input = "Item100 Product200";
string pattern = @"(?<!Item)\d+";

Match match = Regex.Match(input, pattern);
Console.WriteLine(match.Value); // 200

Match digits not preceded by "Item":

Lookbehind support requires fixed-width expressions in C#


3.10 Real-World Examples

📧 Validate Email

string pattern = @"^[\w\.-]+@[\w\.-]+\.\w{2,}$";
Console.WriteLine(Regex.IsMatch("test@example.com", pattern)); // True

📞 Validate Phone Numbers

string pattern = @"^\d{3}-\d{3}-\d{4}$";
Console.WriteLine(Regex.IsMatch("555-123-4567", pattern)); // True

🔗 Extract URLs

string pattern = @"https?:\/\/[\w\.-]+\.\w+";
string text = "Visit https://example.com and http://test.com";

foreach (Match m in Regex.Matches(text, pattern)) {
    Console.WriteLine(m.Value);
}

🔒 Check Password Strength

string pattern = @"^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$";

Console.WriteLine(Regex.IsMatch("Abc123!@", pattern)); // True

3.11 Performance Tips in C#

  • Use RegexOptions.Compiled for reused patterns:
Regex regex = new Regex(pattern, RegexOptions.Compiled);
  • Cache your regex if reused many times
  • Avoid catastrophic backtracking (e.g., (.+)+)

3.12 Test Your C# Regex Online

Use tools like:


3.13 Summary

In this part, you’ve learned how to:

Use regex in C#
Match, replace, and split strings
Use lookaheads, named groups, and options
Validate and extract real-world patterns
Optimize regex in C# applications


🔜 Coming Next

In Part 4, we’ll focus on Real-World Practical Examples — everything from:

  • Email & phone validation
  • File renaming
  • Web scraping
  • Log file analysis

Comments

Popular posts from this blog