1. 程式人生 > >C# 判斷符合要求的16進位制字串格式

C# 判斷符合要求的16進位制字串格式

   /// <summary>
        /// 判斷是否十六進位制格式字串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsHexadecimal(string str)
        {
            const string PATTERN = @"[A-Fa-f0-9]+$";
            bool bo = System.Text.RegularExpressions.Regex.IsMatch(str, PATTERN);

            if(bo == true){
                // 長度判斷 長度+1 與3的餘數為0表示長度符合要求
                if((str.Length+1) % 3 != 0){
                    bo = false;
                }
                else{
                    // 空格判斷,空格數為長度+1 與3的餘數
                    if (str.Length > 2)
                    {
                        
                        string[] arr = str.Split(new char[] { ' ' });

                        //分離後,得到空格數
                        int space_count = arr.Length - 1;

                        //實際空格數
                        int n = ((str.Length + 1) / 3) -1;

                        // 獲得字串中所有的空格數
                        int cout = Regex.Matches(str, @" ").Count;

                        if (space_count != n || cout != space_count)
                        {
                            bo = false;
                        }
                        else
                        {
                            for (int i = 0; i < str.Length; i++)
                            {
                                if ((i + 1) % 3 == 0)
                                { 
                                    // 判斷 2 5 8 11 .. 位置是否為空格
                                    if (str[i] != ' ')
                                    {
                                        bo = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else if (str.Length < 2)
                    {
                        bo = false;
                    } 
                }
            }

            return bo;
        }