using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string text = "124";
if ( !Regex.Match( text, @"^d{5}$" ).Success )
{
Console.WriteLine( "Invalid zip code");
}
}
}
Month: February 2011
Validate city name
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string text = "124 street";
if ( !Regex.Match(text,@"^([a-zA-Z]+|[a-zA-Z]+s[a-zA-Z]+)$" ).Success )
{
Console.WriteLine( "Invalid city");
}
}
}
Validate address
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string text = "124 street";
if ( !Regex.Match( text, @"^[0-9]+s+([a-zA-Z]+|[a-zA-Z]+s[a-zA-Z]+)$" ).Success ) {
Console.WriteLine( "Invalid address");
}
}
}
Validate first name and last name
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string text = "Name";
if ( !Regex.Match(text,"^[A-Z][a-zA-Z]*$" ).Success )
{
Console.WriteLine( "Invalid last name");
}
}
}
Use regular to split string
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
Regex testRegex1 = new Regex( @"d" );
Console.WriteLine( "Original string: " + testString1 );
String[] result = Regex.Split( testString1, @",s" );
foreach ( string resultString in result )
Console.WriteLine(""" + resultString + "", ");
}
}
Use regular expression to replace first 3 digits
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string testString1 = "1, 2, 3, 4, 5, 6, 7, 8";
Regex testRegex1 = new Regex( @"d" );
Console.WriteLine( "Original string: " + testString1 );
Console.WriteLine( "Replace first 3 digits by "digit": " + testRegex1.Replace( testString1, "digit", 3 ) );
}
}
Use regular to replace word
using System;
using System.Text.RegularExpressions;
class RegexSubstitution
{
public static void Main()
{
string testString1 = "a b c stars *****";
Regex testRegex1 = new Regex( @"d" );
Console.WriteLine( "Original string: " + testString1 );
Console.WriteLine( "Every word replaced by "word": " + Regex.Replace( testString1, @"w+", "word" ) );
}
}

