判断字符串是否为数字的方法

1﹑使用Try...Catch

 

        private static bool IsNumeric(string itemValue,int intFLag)
        {
            try
            {
                int i = Convert.ToInt32(itemValue);
                return true;
             }
            catch
            {
               return false;
             }
         }

 

 

2﹑使用正则表达式

 

 

using System.Text.RegularExpressions;
        
         private static bool IsNumeric(string itemValue) 
        {
            return (IsRegEx("^(-?[0-9]*[.]*[0-9]{0,3})$", itemValue));
         }

        private static bool IsRegEx(string regExValue, string itemValue) 
        {
            try 
            {
                 Regex regex = new System.Text.RegularExpressions.Regex(regExValue);
                if (regex.IsMatch(itemValue)) return true;
                else                          return false;
             }
            catch (Exception ) 
            {
                return false;
             }
            finally 
            {
             }
         }

 

 

3﹑判断输入的keyCode

 

 

        public static bool IsNumeric(System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((e.KeyChar >= (char)48 && e.KeyChar<=(char)57) || 
                  e.KeyChar ==(char)8 || e.KeyChar ==(char)45 || e.KeyChar ==(char)47)
            {
             }
            else
            {
     e.Handled=true; 
             }
            return true;
         }
public static bool isNumeric(string strInput)
    {

        char[] ca = strInput.ToCharArray();
        bool found = true;
        for (int i = 0; i < ca.Length; i++)
        {
            if ((ca[i] < '0' || ca[i] > '9') && ca[i] != '.')
            {

                found = false;
                break;

            };

        };
        return found;

    }

 

你可能感兴趣的:(windows,正则表达式)