
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Pattern matching in C# with Regex
A regular expression is a pattern that could be matched against an input text. A pattern consists of one or more character literals, operators, or constructs.
Let us see an example to display the words starting with the letter ‘M’ using Regex.
Example
using System; using System.Text.RegularExpressions; namespace Demo { class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "Mandatory requirements for a Cricket Match Event!"; Console.WriteLine("Matching words that start with 'M': "); showMatch(str, @"\bM\S*"); Console.ReadKey(); } } }
Output
Matching words that start with 'M': The Expression: \bM\S* Mandatory Match
Above, I have the string.
string str = "Mandatory requirements for a Cricket Match Event!";
To get all the words that begin with ‘M’, I have used the following pattern −
@"\bM\S*
- Related Articles
- Pattern matching in Python with Regex
- What is Pattern Matching in C# 7.0?
- Wildcard Pattern Matching
- Matching Nonprintable Characters using Java regex
- Unix filename pattern matching in Python
- Unix filename pattern matching in Python (fnmatch)
- Which package is used for pattern matching with regular expressions in java?
- Print all words matching a pattern in CamelCase Notation Dictionary in C++
- Lua pattern matching vs regular expression
- Methods of the Pattern class in Java Regex
- Program to check regular expression pattern is matching with string or not in Python
- How to return all matching strings against a RegEx in JavaScript?
- Matching strings with a wildcard in C#
- MySQL pattern matching 3 or more “a's” in name?
- Camelcase Matching in C++

Advertisements