栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

c#正则表达式——替换

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c#正则表达式——替换

 string pattern = "(mr|dr) ([A-Z])[a-z]*";
            string str = "mr Jhons$,dr Tom$";
            Regex regex = new Regex(pattern);

            var ouputStr = regex.Replace(str, "Mr X");
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            ouputStr = regex.Replace(str, "$1 X");//$group,使用group指定的组号
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            ouputStr = regex.Replace(str, "$2 X");//$group,使用group指定的组号
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            ouputStr = regex.Replace(str, "$+ X");//把找到的匹配使用最后一个组替换
            Console.WriteLine(ouputStr);

         
            

            Console.WriteLine();
            pattern = "(?mr|dr) ([A-Z])[a-z]*";
            regex = new Regex(pattern);
            ouputStr = regex.Replace(str, "${groupName} X");//把找到的所有匹配使用groupName替换
            Console.WriteLine(ouputStr);


            Console.WriteLine();
            pattern = "mr [A-Z][a-z]*";
            str = "mr Jhons!";
            regex = new Regex(pattern);
            ouputStr = regex.Replace(str, "$");//把找到的匹配使用$替换
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            pattern = "mr [A-Z][a-z]*";
            str = "@!mr Jhons";
            regex = new Regex(pattern);
            ouputStr = regex.Replace(str, "$`");//把找到的匹配使用匹配前的文本去替换,在这里匹配前的文本是"@!"。
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            pattern = "mr [A-Z][a-z]*";
            str = "%mr Jhons@!";
            regex = new Regex(pattern);
            ouputStr = regex.Replace(str, "$'");//把找到的匹配使用匹配后的文本去替换,在这里匹配后的文本是"@!"。
            Console.WriteLine(ouputStr);

            Console.WriteLine();
            pattern = "mr [A-Z][a-z]*";
            str = "%mr Jhons@!";
            regex = new Regex(pattern);
            ouputStr = regex.Replace(str, "$_");//把找到的匹配使用整个的字符串,也就是str的值来替换
            Console.WriteLine(ouputStr);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909806.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号