Regular expression is a pattern that could be matched against an input text. The .NET framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.
For example, if you want to match words that begin with ‘S’, use Regular Expressions in C# as shown in the following code −
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 = "Email Sent Today!";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}Output
Matching words that start with 'S': The Expression: \bS\S* Sent
The Regex class for regular expressions in C# has the following methods:
| Sr.No | Method & Description |
|---|---|
| 1 | public bool IsMatch(string input) Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string. |
| 2 | public bool IsMatch(string input, int start) Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string. |
| 3 | public static bool IsMatch(string input, string pattern) Indicates whether the specified regular expression finds a match in the specified input string. |
| 4 | public MatchCollection Matches(string input) Searches the specified input string for all occurrences of a regular expression. |
| 5 | public string Replace(string input, string replacement) In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string. |
| 6 | public string[] Split(string input) Splits an input string into an array of sub strings at the positions defined by a regular expression pattern specified in the Regex constructor. |