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