What are regular expressions in C#

CsharpProgrammingServer Side Programming

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 −


 Live Demo

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) {
      static void Main(string[] args) {
         string str = "Email Sent Today!";

         Console.WriteLine("Matching words that start with 'S': ");
         showMatch(str, @"\bS\S*");


Matching words that start with 'S':
The Expression: \bS\S*

The Regex class for regular expressions in C# has the following methods:

Sr.NoMethod & Description
1public bool IsMatch(string input)
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
2public 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.
3public static bool IsMatch(string input, string pattern)
Indicates whether the specified regular expression finds a match in the specified input string.
4public MatchCollection Matches(string input)
Searches the specified input string for all occurrences of a regular expression.
5public 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.
6public 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.
Published on 06-Aug-2018 11:36:54