Regex中Replace方法的简单实用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
 
namespace _04字符替换
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 字符串替换
            /*
             使用正则替换字符串
             */
            string msg = "你aaa好aa哈哈a";
            msg = Regex.Replace(msg, @"a+","A");
            Console.WriteLine(msg);
 
            /*
             替换中使用提取组
            在替换中也是可以使用提取组的 $表示提取组 $1表示组1  (引用正则表达式提取的字符串)
            */
            string msg2 = "Hello 'welcome' to 'china'"; 
            msg2 = Regex.Replace(msg2, "'(.+?)'", "[$1]");
            Console.WriteLine(msg2);
 
            /*
             隐藏手机号码
             */
            string msg3 = "文天祥12345678911";
            msg3 = Regex.Replace(msg3, "([0-9]{4})[0-9]{4}([0-9]{3})", "$1****$2"); 
            Console.WriteLine(msg3);
 
            /*
             隐藏邮箱名
             */
            string msg4 = "123456789@qq.com";
            msg4 = Regex.Replace(msg4, "(.+?)@", "*****");
            Console.WriteLine(msg4);
            #endregion
 
            Console.ReadKey();
        }
    }
}

 

 

 引用:https://www.cnblogs.com/zhaoyl9/p/14215102.html

posted @ 2021-02-25 17:16  HarryK  阅读(310)  评论(0编辑  收藏  举报