Regular Expressions are used to manipulate the text data. In general Regular Expression is applied on string.
In C# we can create our own Regular Expression by using System.Text.RegularExpressions namespace. In this article we create simple Regular Expression to split the data.
Open Microsoft Visual Studio, Create new Console Application and add below code.
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace CSharpRegularExpression
{
class Program
{
static void Main(string[] args)
{
string sNames = "John,Bob, Raj, Smith";
Regex regExp = new Regex(" |, |,");
StringBuilder sbNames = new StringBuilder();
int iNumber = 1;
foreach (string subString in regExp.Split(sNames))
{
sbNames.AppendFormat(
"{0}: {1}\n", iNumber++, subString);
}
Console.WriteLine("{0}", sbNames);
Console.ReadLine();
}
}
}
As shown above we have comma separated names and we are splitting these names by using Regular Expression " |, |,". The output displays as shown below.
CSharpRegularExpression.zip (23.14 kb)