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*