为什么这个C#Regular Expression会崩溃我的程序?

时间:2010-03-20 21:31:49

标签: c# regex

using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace Working
{
    class Program4
    {
        static string errorurl = 
               "http://www.realtor.ca/propertyDetails.aspx?propertyId=8692663";

        static void Main(string[] args)
        {
            string s;

            s = getWebpageContent(errorurl);

            s = removeNewLineCharacters(s);

            getFields(s);

            Console.WriteLine("End");
        }


        public static void getFields(string html)
        {
            Match m;
            string fsRE = @"ismeasurement.*?>.*?(\d+).*?sqft";
            m = Regex.Match(html, fsRE, RegexOptions.IgnoreCase);
        }

        private static string removeNewLineCharacters(string str)
        {
            string[] charsToRemove = new string[] { "\n", "\r" };

            foreach (string c in charsToRemove)
            {
                str = str.Replace(c, "");
            }

            return str;
        }


        static string getWebpageContent(string url)
        {
            WebClient client = new WebClient();

            client.Headers.Add("user-agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; 
                          .NET CLR 1.0.3705;)");

            Stream data = client.OpenRead(url);
            StreamReader reader = new StreamReader(data);
            string s = reader.ReadToEnd();
            data.Close();
            reader.Close();

            return s;
        }
    }
}

此程序挂起。当我删除RegexOptions.IgnoreCase选项或时,它正确运行 当我删除对removeNewLineCharacters()函数的调用 有人可以告诉我发生了什么事吗?

1 个答案:

答案 0 :(得分:2)

@"ismeasurement.*?>.*?(\d+).*?sqft"

看到这么多懒人比赛,我想在backtracking上花了太多时间。

尝试将其重构为不使用惰性匹配,例如

@"ismeasurement[^>]*>\D*(\d+)\s*sqft"

删除RegexOptions.IgnoreCase的原因是因为该页面中只有字符串“isMeasurement”。删除removeNewLineCharacters的原因是.与新行不匹配,因此可以提早停止。

(BTW,why are you matching HTML with Regex?)