码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-08-16 13:18:55      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:sys   表达式   void   apt   system   write   去掉   regex   line   

案例一、

如 "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);
                    }
                }
            }
        }

 

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

标签:sys   表达式   void   apt   system   write   去掉   regex   line   

原文地址:http://www.cnblogs.com/zoro-zero/p/7372806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!