正则替换实例-Regex.Replace

 
//实例1
string msg = "你aaa好aa啊!a哈哈";
msg = Regex.Replace(msg, "a+", "A");
//输出结果  你A好A啊!A哈哈  把多个相同的字符替换成一个

//实例2
string msg2 = "wer 'adsf' adf 'asfdasdf' adsf 'ss  'asdff";
msg2 = Regex.Replace(msg2, "'(.+?)'", "【$1】");
//输出结果  wer 【adsf】 adf 【asfdasdf】 adsf 【ss  】asdf

//实例3
string msg3 = "罗分明18312345678lqwvje15288888888";
msg3 = Regex.Replace(msg3, "([0-9]{3})[0-9]{4}([0-9]{4})", "$1****$2");
//输出结果罗分明183****5678lqwvje152****8888

//实例4
string msg4 = "tomorrow row";//把row改为line  tomorrow中的row不能更换
msg4 = Regex.Replace(msg4, @"\brow\b", "line");

//实例5
string msg5 = "hao are you,welcome to you";//找出句子中三个字母的单词
MatchCollection mc = Regex.Matches(msg5, @"\b[a-z]{3}\b", RegexOptions.IgnoreCase);//RegexOptions.IgnoreCase不区分大小写
StringBuilder sb = new StringBuilder();
foreach(Match m in mc)
{
    sb.AppendLine(m.Value);
}

//实例6
string msg6 = "# ### #### ### ## # ###";
MatchCollection mc2 = Regex.Matches(msg6, @"\b###\b");//输出的是0个,因为\b是单词标识
StringBuilder sb2 = new StringBuilder();
foreach (Match m in mc2)
{
    sb2.AppendLine(m.Value);
}

//实例7
string msg7 = "我是罗罗罗分分明明明明明";
msg7= Regex.Replace(msg7, @"(.)\1+","$1");

//实例8
string msg8 = "提取年月日07/09/2017提取年月日07/09/2017";//提取之后格式变为
msg8 = Regex.Replace(msg8, @"(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2");

评论