示例:
string number = "18512345678";
int length = 1;
string result = number.HideMobileMiddleNumber(length, '*');
/*
* length result
* 0 18512345678
* 1 185*2345678
* 2 185**345678
* 3 185***45678
* 4 185****5678
* 5 185*****678
* 6 185******78
* 7 185*******8
* 8 185********
*/
函数主体:
/// <summary>
/// 隐藏手机号中间号码
/// </summary>
/// <param name="number">要隐藏的手机号码</param>
/// <param name="lenght">中间号码的长度,0-8位,0位表示不隐藏,8位表示除了开头的都隐藏</param>
/// <param name="hideChar">被隐藏的号码的替换字符</param>
/// <returns></returns>
public static string HideMobileMiddleNumber(this string number, int lenght, char hideChar)
{
string result = string.Empty;
//空的字符串就返回空的
if (string.IsNullOrEmpty(number)) return null;
//长度不对就抛异常
if (lenght < 0 || lenght > 8)
throw new ArgumentException("length 只能在 0-8 之间");
//构建正则表达式
Regex regex = new Regex(@"(\+86)?(1[34578]\d)(\d{" + lenght + @"})(\d{" + (8 - lenght) + "})");
//正则分组替换
if (!regex.IsMatch(number)) return null;
else result = regex.Replace(number, string.Format("$1$2{0}$4", "".PadLeft(lenght, hideChar)));
//返回结果
return result;
}