C# Regular Expressions

A regular expression in C#, is simply a pattern that could be matched against an input text. The .NET framework gives a regular expression engine that allows such type of matching.

There are the following categories of characters, operators, and constructs that provides you to define a regular expression in C#:

  • character escapes
  • character classes
  • grouping constructs
  • anchors
  • quantifiers
  • backreference constructs
  • substitutions
  • alternation constructs
  • miscellaneous constructs

C# Regular Expression Example

Here is an example program, illustrates the concept and use of regular expression in C# programming. This C# program simply matches all the words that starts with the letter 'S'

/* C# Regular Expression - Example Program */
using System;
using System.Text.RegularExpressions;

namespace RegularExpressionExample
	class RegularExpressionClass
		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 = "This is C Sharp Regular Expression Tutorial at codescracker";
			Console.WriteLine("Matching words that start with 'S':");
			showMatch(str, @"\bS\S*");

When we compile and run the above program then we will get the following output:

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

C# Online Test

« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋