Regular Expressions

Back

Loading concept...

🔍 Regular Expressions in C#: The Pattern Detective

The Story of the Word Detective 🕵️

Imagine you’re a detective. Your job? Finding specific words hidden in a giant book. But here’s the twist—you don’t know exactly what you’re looking for. Maybe you need “all phone numbers” or “every email address” or “words that start with ‘cat’.”

Regular Expressions (or Regex for short) are your detective magnifying glass. They help you find patterns in text—not just exact words, but types of words.


🎯 What is a Regular Expression?

A Regular Expression is a special code that describes a pattern.

Think of it like this:

  • Normal search: “Find the word ‘cat’”
  • Regex search: “Find any word that starts with ‘c’ and ends with ‘t’”
graph TD A["Your Text"] --> B["Regex Pattern"] B --> C{Match Found?} C -->|Yes| D["✅ Found It!"] C -->|No| E["❌ Keep Looking"]

🧰 Getting Started: The Regex Namespace

In C#, regex lives in a special toolbox:

using System.Text
    .RegularExpressions;

This one line unlocks all regex powers!


📝 Basic Patterns: Your First Detective Tools

1. Literal Characters (Exact Match)

The simplest pattern—just type what you want to find:

string text = "I love cats";
string pattern = "cat";
bool found = Regex.IsMatch(
    text, pattern);
// found = true ✅

Like asking: “Is ‘cat’ hiding in this sentence?”


2. The Dot (.) — The Wildcard

The dot matches ANY single character.

string pattern = "c.t";
// Matches: cat, cut, cot, c9t
// Not: ct, cart

Imagine: The dot is a blank tile in Scrabble—it can be anything!


3. Character Classes […] — Pick One From the List

Square brackets let you say “match ONE of these characters”:

string pattern = "[aeiou]";
// Matches any vowel

string pattern2 = "[0-9]";
// Matches any digit

Like a vending machine: Press A, E, I, O, or U—any one will work!


4. Negated Classes [^…] — NOT These!

Add ^ inside brackets to say “anything EXCEPT these”:

string pattern = "[^0-9]";
// Matches anything that's
// NOT a digit

🔢 Quantifiers: How Many?

Quantifiers tell regex how many times to look for something.

Symbol Meaning Example
* Zero or more a* → “”, “a”, “aaa”
+ One or more a+ → “a”, “aaa” (not “”)
? Zero or one a? → “”, “a”
{n} Exactly n a{3} → “aaa”
{n,m} Between n and m a{2,4} → “aa”, “aaa”, “aaaa”
string pattern = @"\d{3}-\d{4}";
// Matches: 123-4567
// (3 digits, dash, 4 digits)

🚀 Special Shortcuts

C# gives you handy shortcuts:

Shortcut Meaning Same As
\d Any digit [0-9]
\D NOT a digit [^0-9]
\w Word character [a-zA-Z0-9_]
\W NOT word char [^a-zA-Z0-9_]
\s Whitespace Space, tab, newline
\S NOT whitespace Everything else
string pattern = @"\d\d\d";
// Same as [0-9][0-9][0-9]
// Matches: 123, 456, 789

Pro tip: Use @ before strings to avoid escaping backslashes!


📍 Anchors: Where to Look?

Anchors don’t match characters—they match positions.

Anchor Meaning
^ Start of string
$ End of string
\b Word boundary
string pattern = @"^Hello";
// Only matches if text
// STARTS with "Hello"

string pattern2 = @"endquot;;
// Only matches if text
// ENDS with "end"

string pattern3 = @"\bcat\b";
// Matches "cat" as whole word
// Not "category" or "scat"

🛠️ Essential Regex Methods

1. IsMatch — Yes or No?

The simplest question: “Does this pattern exist?”

bool exists = Regex.IsMatch(
    "Hello World",
    @"\d");
// exists = false
// (no digits found)

2. Match — Find the First One

Get details about the first match:

Match m = Regex.Match(
    "Order 12345 shipped",
    @"\d+");

Console.WriteLine(m.Value);
// Output: 12345

Console.WriteLine(m.Index);
// Output: 6 (position)

3. Matches — Find ALL of Them

Get every match in the text:

string text = "a1 b2 c3";
MatchCollection all =
    Regex.Matches(text, @"\d");

foreach(Match m in all)
{
    Console.WriteLine(m.Value);
}
// Output: 1, 2, 3

4. Replace — Find and Swap

Replace all matches with something new:

string result = Regex.Replace(
    "Hello 123 World 456",
    @"\d+",
    "###");
// result = "Hello ### World ###"

Like find-and-replace, but smarter!


5. Split — Cut Into Pieces

Split text wherever the pattern matches:

string[] parts = Regex.Split(
    "apple,banana;cherry",
    @"[,;]");
// parts = ["apple",
//          "banana",
//          "cherry"]

🎨 Groups: Capture Parts

Use parentheses () to capture pieces of your match:

string pattern =
    @"(\d{3})-(\d{4})";
Match m = Regex.Match(
    "Call 555-1234",
    pattern);

Console.WriteLine(m.Groups[1]);
// Output: 555

Console.WriteLine(m.Groups[2]);
// Output: 1234

Like highlighting different parts of what you found!


🌟 Real-World Examples

Validate an Email (Simple)

string pattern =
    @"^\w+@\w+\.\w+quot;;

bool valid = Regex.IsMatch(
    "test@example.com",
    pattern);
// valid = true ✅

Extract All Hashtags

string tweet =
    "Love #CSharp and #Regex!";

var tags = Regex.Matches(
    tweet,
    @"#\w+");

foreach(Match t in tags)
    Console.WriteLine(t.Value);
// Output: #CSharp, #Regex

Clean Up Extra Spaces

string messy =
    "Too   many    spaces";

string clean = Regex.Replace(
    messy,
    @"\s+",
    " ");
// clean = "Too many spaces"

🧭 Quick Reference Flow

graph TD A["Need to find text?"] --> B{What do you need?} B -->|Just check exists| C["Regex.IsMatch"] B -->|Get first match| D["Regex.Match"] B -->|Get all matches| E["Regex.Matches"] B -->|Replace text| F["Regex.Replace"] B -->|Split text| G["Regex.Split"]

💡 Remember This!

  1. Regex = Pattern + Text → Find matches
  2. . = Any character
  3. \d = Digit, \w = Word char, \s = Space
  4. * = Zero or more, + = One or more
  5. ^ = Start, $ = End
  6. Use @"pattern" to avoid escape headaches
  7. () groups capture parts of matches

🎉 You Did It!

You now have the detective tools to find any pattern in any text. Regular expressions might look like secret code, but they’re just a way to describe what you’re looking for.

Start simple. Practice often. Soon you’ll be a Regex master! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.