- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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*
Advertisements