Thursday, February 19, 2009

Regular Expression using C#

// Regular Expression Pattern used frequently

// Any Character
// ([A-Z0-9.#();:,>=?' ])

// AlphaNumeric
// (^([\w]|\s)*$)

// Alpha
// (^[a-zA-Z]*$) OR (^(\w)*$)

// Numeric
// (^\d*$)

// Non AlphaNumeric
// (\W*)

// Amount
// (^\d*\.{1}\d{2}$)

// Date(MMDD18/19/20YY)
// ((0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])(18|19|20)\d\d)

// Male or Female
// (M|F)

// Numeric Minium 5 Character
// (\d{5})

// Alpha Exactly 2 Character
// ([a-zA-Z]{2})

// Email
// (^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$)


// Note: Assign pattern like this in a variable
// string strPattern = @"([a-zA-Z]{2})";


// Coding Samples
// AlphaNumericOnly >> Example: TEST 4 ME
public bool isAlphaNumericOnly(string strToCheck)
{
string strPattern = @"(^([\w]|\s)*$)";
Regex RegexPattern = new Regex(@strPattern);
return RegexPattern.IsMatch(strToCheck);
}

// AlphaOnly >> Example: TESTME
public bool isAlphaOnly(string strToCheck)
{
//string strPattern = @"(^(\w)*$)";
string strPattern = @"(^[a-zA-Z]*$)";
Regex RegexPattern = new Regex(@strPattern);
return RegexPattern.IsMatch(strToCheck);
}

// NumericOnly >> Example: 123456
public bool isNumericOnly(string strToCheck)
{
string strPattern = @"(^\d*$)";
Regex RegexPattern = new Regex(@strPattern);
return RegexPattern.IsMatch(strToCheck);
}

// AmountOnly >> Example: 12.25
public bool isAmountOnly(string strToCheck)
{
string strPattern = @"(^\d*\.{1}\d{2}$)";
Regex RegexPattern = new Regex(@strPattern);
return RegexPattern.IsMatch(strToCheck);
}

// DateOnly >> Example: MMDDYYYY (12122001) - valid year start with 18, 19, 20
public bool isDateOnly(string strToCheck)
{
string strPattern = @"((0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])(18|19|20)\d\d)";
Regex RegexPattern = new Regex(@strPattern);
return RegexPattern.IsMatch(strToCheck);
}

// Alternative way to check valid date, like leap or so
// DateOnly >> Example: MMDDYYYY (12122001)
public bool isValidDate(string date)
{
try
{
String format = "MMddyyyy"; // mmddyyyy
System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();
dtfi.ShortDatePattern = format;
DateTime dt = DateTime.ParseExact(date, "d", dtfi);
}
catch (Exception)
{
return false;
}
return true;
}

No comments: