Friday, 7 September 2012

Word count example through Regular expression in c#


using System.Text.RegularExpressions;
 
public static class Validations
{
       public static int WordCount(string inputStr)
        {
            int RetVal = 0;

            try
            {
                // Exclude whitespaces, Tabs and line breaks
                var RegExp = new Regex(@"[^\s]+");
                var Matches = RegExp.Matches(inputStr);
                RetVal = Matches.Count;
            }
            catch (Exception)
            {
            }

            return RetVal;
        }

        public static bool IsDecimalValue(string str)
        {
            if (Regex.IsMatch(str, @"^[0-9]+(\.[0-9]{1,10})?$",
                RegexOptions.IgnorePatternWhitespace))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool IsAlphaEntry(string str)
        {
            if (Regex.IsMatch(str, @"[a-zA-Z][a-zA-Z]+",
                RegexOptions.IgnorePatternWhitespace))
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        public static bool IsAlphaNumericEntry(string str)
        {
            if (Regex.IsMatch(str, @"^[0-9a-zA-Z]+$",
                RegexOptions.IgnorePatternWhitespace))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool IsNumericEntry(string str)
        {
            if (Regex.IsMatch(str, @"^[0-9]+$",
                RegexOptions.IgnorePatternWhitespace))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool IsValidEmailAddress(string str)
        {

            if (Regex.IsMatch(str, @"^[A-Za-z0-9_\-\.]+@(([A-Za-z0-9\-])+\.)+([A-Za-z\-])+$",
                RegexOptions.IgnorePatternWhitespace))
            {
                return true;
            }
            else
            {
                return false;
            }
        }       
}

No comments:

Post a Comment