codescracker


c#

C# Regular Expressions



« Previous Tutorial Next Tutorial »


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#:

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)
			{
				Console.WriteLine(m);
			}
		}
		
		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*");
			Console.ReadKey();
		}	
	}
}

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*
Sharp

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test