C# 正则表达式贪婪模式案例

案例一、

如 "acbacb"  正则  "a.*?b" 只会取到第一个"acb" 原本可以全部取到但加了限定符后,只会匹配尽可能少的字符 ,而"acbacb"最少字符的结果就是"acb" 。

案例二、

复制代码
/// <summary>
        /// 去掉<script>标签
        /// </summary>
        static void Test2()
        {
            //要匹配的字符串  
            string text = @"hello
                            <script>
                            alert('1');
                            </script>
                            regex
                            <script>
                            alert('2');
                            </script>
                            world";
            //正则表达式  
            string pattern = @"<script>[\s\S]*?</script>";
            //string result = Regex.Replace(text, pattern, "").Replace("\r\n","").Replace(" ","");
            string result = Regex.Replace(text, pattern, "").Replace(" ", "");
            Console.WriteLine(result);
        }

        /// <summary>
        /// 获取<script>标签内容
        /// </summary>
        static void Test3()
        {
            //要匹配的字符串  
            string text = @"hello
                            <script>
                            alert('1');
                            </script>
                            regex
                            <script>
                            alert('2');
                            </script>
                            world";
            //正则表达式  
            string pattern = @"<script>[\s\S]*?</script>";
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
            //string result = Regex.Replace(text, pattern, "").Replace("\r\n","").Replace(" ","");
            MatchCollection matchCollection = r.Matches(text);
            foreach (Match m in matchCollection)
            {
                //显示匹配开始处的索引值和匹配到的值  
                System.Console.WriteLine("Match=[" + m + "]");
                CaptureCollection cc = m.Captures;
                foreach (Capture c in cc)
                {
                    Console.WriteLine("/tCapture=[" + c + "]");
                }
                for (int i = 0; i < m.Groups.Count; i++)
                {
                    Group group = m.Groups[i];
                    System.Console.WriteLine("/t/tGroups[{0}]=[{1}]", i, group);
                    for (int j = 0; j < group.Captures.Count; j++)
                    {
                        Capture capture = group.Captures[j];
                        Console.WriteLine("/t/t/tCaptures[{0}]=[{1}]", j, capture);
                    }
                }
            }
        }
复制代码

 

posted @   大空白纸  阅读(1980)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示