9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 40 views

πŸš€ C# Regular Expressions – Master Pattern Matching in Strings


🧲 Introduction – Why Use Regular Expressions in C#

Regular expressions (regex) allow you to define powerful patterns for matching, searching, and manipulating text. In C#, the System.Text.RegularExpressions namespace provides full support for regex-based operations, making it a powerful tool for input validation, string parsing, and text extraction.

🎯 In this guide, you’ll learn:

  • What regular expressions are and how to write them
  • How to use the Regex class in C#
  • Real-world use cases: email validation, text searching, replacements
  • Common regex patterns and best practices

πŸ” Core Concept – What Are Regular Expressions?

A regular expression is a string pattern made up of characters and symbols that define a search or matching rule.

Example Pattern:

^\d{3}-\d{2}-\d{4}$

βœ… Matches U.S. Social Security numbers like 123-45-6789


πŸ“š Key Regex Classes in C#

ClassPurpose
RegexCore class to match/replace/search
MatchRepresents a single match
MatchCollectionRepresents all matches found
GroupRepresents a subexpression match

πŸ’» Code Example – Regex Match

using System;
using System.Text.RegularExpressions;

class RegexExample
{
    static void Main()
    {
        string pattern = @"\d+";
        string input = "There are 123 apples and 45 oranges.";

        MatchCollection matches = Regex.Matches(input, pattern);
        
        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
    }
}

πŸ“€ Output:

123  
45

πŸ› οΈ Common Regex Patterns

PatternDescriptionExample Match
\dDigit0-9
\wWord charactera-z, A-Z, 0-9
\sWhitespacespace, tab, newline
.Any character (except newline)a, b, 1, etc.
^Start of string
$End of string
*, +, ?Zero/more, one/more, zero/one\d+ matches 1+ digits
[]Character set[aeiou]
``OR
()Grouping(abc)+

πŸ” Replace with Regex

string input = "Call me at 123-456-7890";
string masked = Regex.Replace(input, @"\d{3}-\d{3}-\d{4}", "***-***-****");

Console.WriteLine(masked);  // Output: Call me at ***-***-****

βœ… Use Case Examples

  • Email validation: ^[\w\.-]+@[\w\.-]+\.\w+$
  • Phone number masking
  • Extracting numbers or words
  • Parsing logs or structured text

πŸ’‘ Tips, Pitfalls & Best Practices

πŸ’‘ Tip: Use regex101.com to test patterns interactively.

⚠️ Pitfall: Regex patterns can become hard to read. Always comment or document complex ones.

πŸ“˜ Best Practice: Use named groups for clarity:

(?<area>\d{3})-(?<exchange>\d{3})-(?<line>\d{4})

πŸ“Œ Summary – Recap & Next Steps

C# regular expressions are essential for powerful text parsing and validation. With Regex, you can search, extract, and transform strings efficiently.

πŸ” Key Takeaways:

  • Use Regex.Match(), Regex.Matches(), and Regex.Replace() for powerful string operations
  • Learn basic pattern symbols like \d, \w, ^, $
  • Master use cases like input validation and data extraction

βš™οΈ Up next: Dive into πŸš€ C# Preprocessor Directives to control compilation with #if, #define, and more.


❓ FAQ – C# Regular Expressions

❓ What namespace contains Regex in C#?
βœ… System.Text.RegularExpressions

❓ Can regex be case-insensitive?
βœ… Yes. Use RegexOptions.IgnoreCase.

❓ What’s the difference between Match and Matches?
βœ… Match finds the first match; Matches returns all matches as a collection.

❓ Are regex expressions compiled?
βœ… You can use RegexOptions.Compiled for faster repeated execution.

❓ Can I validate email or phone numbers with regex?
βœ… Yes. Regex is commonly used for format validation.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Regular Expressions

Or Copy Link

CONTENTS
Scroll to Top