欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 判断字符串是否为2进制,8进制,10进制,16进制

程序员文章站 2024-03-18 20:50:58
...
        /// <summary>  
        /// 判断是否二进制格式字符串  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>true 是  false 不是</returns>  
        public static bool IsBinary(string str)
        {
            if (str == "")
                return false;
            const string PATTERN = @"[0-1]+$";
            bool sign = false;
            for (int i = 0; i < str.Length; i++)
            {
                sign = System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), PATTERN);
                if (!sign)
                {
                    return sign;
                }
            }
            return sign;
        }

        /// <summary>  
        /// 判断是否八进制格式字符串  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>true 是  false 不是</returns>  
        public static bool IsOctal(string str)
        {
            if (str == "")
                return false;
            const string PATTERN = @"[0-7]+$";
            bool sign = false;
            for (int i = 0; i < str.Length; i++)
            {
                sign = System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), PATTERN);
                if (!sign)
                {
                    return sign;
                }
            }
            return sign;
        }

        /// <summary>  
        /// 判断是否十进制格式字符串  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>true 是  false 不是</returns>  
        public static bool IsDecimal(string str)
        {
            if (str == "")
                return false;
            const string PATTERN = @"[0-9]+$";
            bool sign = false;
            for (int i = 0; i < str.Length; i++)
            {
                sign = System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), PATTERN);
                if (!sign)
                {
                    return sign;
                }
            }
            return sign;
        }

        /// <summary>
        /// 判断是否十六进制格式字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool IsHexadecimal(string str)
        {
            if (str == "")
                return false;
            const string PATTERN = @"[A-Fa-f0-9]+$";
            bool sign = false;
            for (int i = 0; i < str.Length; i++)
            {
                sign = System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), PATTERN);
                if (!sign)
                {
                    return sign;
                }
            }
            return sign;  
        }