π 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
Regexclass 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#
| Class | Purpose |
|---|---|
Regex | Core class to match/replace/search |
Match | Represents a single match |
MatchCollection | Represents all matches found |
Group | Represents 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
| Pattern | Description | Example Match |
|---|---|---|
\d | Digit | 0-9 |
\w | Word character | a-z, A-Z, 0-9 |
\s | Whitespace | space, 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(), andRegex.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 :
