Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. C# Regex Examples

C# Regex Examples

Date- May 19,2023 Updated Jan 2026 4171
C# Regex Examples csharp

Overview of the Regex Class

The Regex class in C# is part of the System.Text.RegularExpressions namespace and provides a rich set of functionalities for working with regular expressions. Regular expressions are sequences of characters that define a search pattern, primarily used for string pattern matching. The power of regex lies in its ability to perform complex searches and manipulations with minimal code.

In real-world applications, regex can be used for a variety of tasks, such as validating email addresses, parsing log files, and even extracting information from text documents. Its versatility makes it an essential tool for developers who need to handle textual data efficiently.

Match

The Match method is designed to find the first occurrence of a specified pattern within a given string. When a match is found, it returns a Match object that contains valuable information, including the index of the match and the matched substring itself.

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string text = "The quick brown fox jumps over the lazy dog.";
        string pattern = "fox";
        Match match = Regex.Match(text, pattern);
        if (match.Success) {
            Console.WriteLine("Match found at index " + match.Index);
        } else {
            Console.WriteLine("No match found.");
        }
    }
}

In this example, the program searches for the word 'fox' in the provided text. If a match is found, it outputs the index of the match; otherwise, it indicates that no match was found.

Matches

The Matches method is used to find all occurrences of a specified pattern within a string. Unlike the Match method, which returns only the first match, Matches returns a collection of Match objects that can be iterated over.

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string text = "The quick brown fox jumps over the lazy dog.";
        string pattern = @"\b\w{4}\b"; // Matches four-letter words
        MatchCollection matches = Regex.Matches(text, pattern);
        foreach (Match match in matches) {
            Console.WriteLine("Match found: " + match.Value);
        }
    }
}

This code snippet demonstrates how to find and print all four-letter words in the input string. The regex pattern \b\w{4}\b matches any word that consists of exactly four letters.

Replace

The Replace method allows you to substitute occurrences of a pattern within a string with a specified replacement string. This is particularly useful for tasks such as sanitizing user input or formatting text.

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string text = "The quick brown fox jumps over the lazy dog.";
        string pattern = @"\b\w{4}\b"; // Matches four-letter words
        string replacement = "****";
        string result = Regex.Replace(text, pattern, replacement);
        Console.WriteLine("Result: " + result);
    }
}

In this example, all four-letter words in the input string are replaced with asterisks. This demonstrates how you can use regex to mask sensitive information.

Additional Regex Methods

Beyond Match, Matches, and Replace, the Regex class offers several other useful methods:

  • IsMatch: Determines if a pattern exists within a string and returns a boolean value.
  • Split: Divides a string into an array based on a specified pattern.
  • Escape: Escapes special characters in a string so that they can be used in a regex pattern.

Here’s an example of using the IsMatch method:

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string email = "example@domain.com";
        string pattern = @"^[^\s@]+@[^\s@]+\.[^\s@]+$"; // Simple email validation
        bool isValid = Regex.IsMatch(email, pattern);
        Console.WriteLine("Is the email valid? " + isValid);
    }
}

This code checks if the given email address matches a simple regex pattern for email validation.

Edge Cases & Gotchas

When working with regular expressions, it's essential to be aware of potential edge cases and gotchas that can lead to unexpected results:

  • Greedy vs. Lazy Matching: By default, regex uses greedy matching, which means it will match as much text as possible. To perform lazy matching, you can append a '?' to the quantifier (e.g., *? or +?).
  • Escape Special Characters: Many characters have special meanings in regex (e.g., ., *, ?, +). If you need to match these characters literally, ensure you escape them using a backslash.
  • Performance Issues: Complex regex patterns can lead to performance issues, especially when used on large datasets. Always test your regex against realistic data sizes.

Performance & Best Practices

To ensure optimal performance when using regex in C#, consider the following best practices:

  • Compile Regex Patterns: If you are using the same regex pattern multiple times, consider compiling it using RegexOptions.Compiled for better performance.
  • Minimize Backtracking: Avoid patterns that lead to excessive backtracking by using specific quantifiers and avoiding nested quantifiers when possible.
  • Test Thoroughly: Always test your regex patterns with a variety of input data to ensure they work as expected and handle edge cases appropriately.

Conclusion

Regular expressions are an invaluable tool for text processing in C#. By mastering the Regex class and its various methods, you can efficiently handle a wide range of text manipulation tasks. Here are some key takeaways:

  • The Regex class is part of the System.Text.RegularExpressions namespace.
  • Use Match, Matches, and Replace methods for common string operations.
  • Be aware of edge cases and potential performance issues when using regex.
  • Follow best practices to optimize regex usage in your applications.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering Type Casting in C#: A Complete Guide with Examples
Dec 09, 2023
Complete Guide to Access Modifiers in C# with Examples
Dec 09, 2023
Mastering Microsoft Word Document Generation in ASP.NET Core with Open XML SDK
Apr 24, 2026
Integrating Square Payments API in ASP.NET Core for POS and Online Payments
Apr 18, 2026
Previous in C#
Get IP address using c#
Next in C#
How to Generate Image using C#
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 367 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11588 views
  • The report definition is not valid or is not supported by th… 10962 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9937 views
  • Get IP address using c# 8773 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor