1、替换最后一个字符
dto.ContactPerson = dto.ContactPerson.ReplaceName("*");
/// <summary>
/// 替换最后一个字符串
/// </summary>
/// <param name="oldStr"></param>
/// <param name="newStr"></param>
/// <returns></returns>
public static string ReplaceName(this string oldStr, string newStr)
{
string pattern = @"(.)$";
string result = Regex.Replace(oldStr, pattern, newStr);
return result;
}
2、替换除第一字符外其他都替换成*
**注意:**new string('*', m.Groups[2].Length) 是表示根据第一个字符后又几个字符来生成相应得*号来替换
dto.ContactPerson = dto.ContactPerson.ReplaceName();
/// <summary>
/// 替换第一个字符后得其他字符串
/// </summary>
/// <param name="oldStr"></param>
/// <param name="newStr"></param>
/// <returns></returns>
public static string ReplaceStr(this string oldStr)
{
// 正则表达式:匹配第一个字符之后的所有字符
string pattern = "(.)(.*)";
string result = Regex.Replace(oldStr, pattern, m => m.Groups[1].Value + new string('*', m.Groups[2].Length));
return result;
}
或则自定义替换成你想要得字符
dto.ContactPerson = dto.ContactPerson.ReplaceStr('-');
/// <summary>
/// 替换第一个字符后得其他字符串
/// </summary>
/// <param name="oldStr"></param>
/// <param name="newStr"></param>
/// <returns></returns>
public static string ReplaceStr(this string oldStr, char newStr)
{
// 正则表达式:匹配第一个字符之后的所有字符
string pattern = "(.)(.*)";
string result = Regex.Replace(oldStr, pattern, m => m.Groups[1].Value + new string(newStr, m.Groups[2].Length));
return result;
}
3、隐藏手机号
dto.ContactNumber = PhoneExtensions.GetPhoneHidden(demand.ContactNumber);
/// <summary>
/// 获取隐藏中间四位的手机号码
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public static string GetPhoneHidden(this string phone, bool isValidateTelePhone = true)
{
//如果固化则不隐藏
if (isValidateTelePhone && IsTelePhoneNumber(phone))
{
return phone;
}
return Regex.Replace(phone, "(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
/// <summary>
/// 验证固定电话号码
/// [3位或4位区号;区号可以用小括号括起来;区号可以省略;区号与本地号间可以用减号或空格隔开;可以有3位数的分机号,分机号前要加减号]
/// </summary>
/// <param name="input">待验证的字符串</param>
/// <returns>是否匹配</returns>
public static bool IsTelePhoneNumber(string input)
{
string pattern = @"^(((0\d2|0\d{2})[- ]?)?\d{8}|((0\d3|0\d{3})[- ]?)?\d{7})(-\d{3})?$";
return IsMatch(input, pattern);
}