Tuesday, June 19, 2007

One liner - (Tips and Tricks) String pattern matching - RegEx()

Most of you know but sometimes we keep wondering best ways to do this. RegEx is the solution in .net for any type of string matching pattern.

More details on RegEx visit - http://msdn2.microsoft.com/en-us/library/az24scfc.aspx

RegEx is part of System.Text.RegularExpressions Namespace
How to verify if an email is valid in .net?
Trick -

bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}

How to remove/strip invalid characters from a string using RegEx in .net?
Trick -

String CleanInput(string strIn)
{
// Replace invalid characters with empty strings.
return Regex.Replace(strIn, @"[^\w\.@-]", "");
}

How to check if a particular character within a string is alphabet/char or alphanumeric or hexa?
Trick (alpha) - (checks if first char is alphabet)

return Regex.IsMatch(yourString.Substring(0,1), @"[a-zA-Z]");

HTH - Dipesh

No comments: