替换正则表达式c#

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);

}

相关推荐
半梦半醒*1 天前
正则表达式
linux·运维·开发语言·正则表达式·centos·运维开发
mudtools1 天前
.NET驾驭Word之力:COM组件二次开发全攻略之连接Word与创建你的第一个自动化文档
后端·c#
王维志1 天前
LiteDB详解
数据库·后端·mongodb·sqlite·c#·json·database
程序猿多布1 天前
XLua教程之热补丁技术
unity·c#·lua·xlua
咕白m6251 天前
C# Excel 读取入门教程:免费实现方法
c#·.net
相与还1 天前
godot+c#使用godot-sqlite连接数据库
数据库·c#·godot
PyHaVolask1 天前
Python进阶教程:随机数、正则表达式与异常处理
python·正则表达式·异常处理·随机数生成
相与还1 天前
godot+c#操作sqlite并加解密
sqlite·c#·godot·sqlcipher
疯狂的维修1 天前
关于Gateway configration studio软件配置网关
网络协议·c#·自动化·gateway
程序猿多布1 天前
XLua教程之Lua调用C#
unity·c#·lua·xlua