C# 手机号码隐藏中间四位

时间:2024-03-06 08:45:51

C# 隐藏手机号码中间四位数字

  1. 使用正则表达式隐藏手机号中间四位
        if (!string.IsNullOrWhiteSpace(txtPhone.Text) &&
                txtPhone.Text.Length == 11)
            {
                txtPhoneDesendent.Text = Regex.Replace(txtPhone.Text, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            }
  1. 字符串判断处理

            /// <summary>
            /// 手机号脱敏
            /// </summary>
            /// <param name="phoneNo"></param>
            /// <returns></returns>
            private string ConvertPhonedNo(string phoneNo)
            {
                if (string.IsNullOrEmpty(phoneNo))
                    return phoneNo;
                if (phoneNo.Length < 11)
                {
                    return phoneNo;
                }
                StringBuilder sb = new StringBuilder(phoneNo.Substring(0, 3));
                for (int i = 0; i < phoneNo.Length - 5; i++)
                {
                    sb.Append(\'*\');
                }
                sb.Append(phoneNo.Substring(phoneNo.Length - 2));
                return sb.ToString();
            }