正则表达式替换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace _02正则表达式替换
{
    class Program
    {
        static void Main(string[] args)
        {
            ////把字符串中所有的空格都替换成一个空格。
            //string msg = "hello    thank you  please   u     r welcome   .";
            ////\s+表示:空白符出现一次或多次。
            //msg = Regex.Replace(msg, @"\s+", " ");
            //Console.WriteLine(msg);
            //Console.ReadKey();





            ////练习2:将连续的-都替换成一个-
            //string msg = "234--234--------------34-55";
            //msg = Regex.Replace(msg, @"\-+", "-");
            //Console.WriteLine(msg);
            //Console.ReadKey();




            ////在字符串替换的时候也可以使用提取组。这个时候提取组的
            ////信息在$1 $2 $3...
            //string result = Regex.Replace("年龄=20", "(.+)=(.+)", "$1是$2");
            //Console.WriteLine(result);
            //Console.ReadKey();



            ////把所有的中文双引号都替换成:
            ////"hello【welcome to 】beautiful 【China】"
            //string s1 = "hello“welcome to ”beautiful “China”";

            //s1 = Regex.Replace(s1, "“(.+?)”", "【$1】");
            //Console.WriteLine(s1);
            //Console.ReadKey();

            #region 练习1:将一段文本中的MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式 ,比如“我的生日是05/21/2010耶”转换为“我的生日是2010-05-21耶”。

            //string msg = "我的生日是05/21/2010耶,Ta的生日是06/10/2000.";
            //msg = Regex.Replace(msg, @"(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2");
            //Console.WriteLine(msg);
            //Console.ReadKey();

            #endregion


            #region 练习2:给一段文本中匹配到的url添加超链接,比如把http://www.test.com替换为<a href="http://www.test.com"> http://www.test.com</a>。参考代码见备注。

            ////贪婪模式一般都发生在使用.作为匹配的时候,如果发现无法解决贪婪模式问题
            ////则考虑不用.作为匹配。
            //string html = "这个是百度:http://www.baidu.com ; <br/> 这个是谷歌:http://www.google.com <br/>";
            ////html = Regex.Replace(html, @"(\w+://[a-zA-Z0-9_\-\.&\?=]+)", "<a href=\"$1\">$1</a>");
            ////错误。
            ////html = Regex.Replace(html, html, "===$0=======");
            //Console.WriteLine(html);
            //Console.ReadKey();



            #endregion


            #region UBB代码替换

            //string UbbHtml = "想养眼的过来啦,有个好[url=http://net.itcast.cn/]网站[/url]还有微软 [b]杨中科[/b]的网址:[url=http://net.itcast.cn/]网站[/url]";
            ////[url=http://net.itcast.cn/]网站[/url]
            //string html = Regex.Replace(UbbHtml, @"\[[uU][rR][lL]=(.+?)\](.+?)\[/[uU][rR][lL]\]", "<a href=\"$1\">$2</a>");
            //html = Regex.Replace(html, @"\[[bB]\](.+?)\[/[bB]\]", "<b>$1</b>");
            //Console.WriteLine(html);
            //Console.ReadKey();

            #endregion

            #region 敏感词过滤



            #endregion


        }
    }
}

原文地址:https://www.cnblogs.com/zpc870921/p/2640571.html