尝试迭代时,MatchCollection可以挂起程序吗?

时间:2013-08-02 12:08:31

标签: c# regex

我有一个代码示例,当试图将它与foreach一起使用时,MatchCollection似乎挂起程序。

我正在使用CSSParser类解析css:

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

namespace Helpers.Utils
{
    public class CSSParser
    {
        private readonly Dictionary<string, Dictionary<string, string>>
            _dict = new Dictionary<string, Dictionary<string, string>>();

        private const string SelectorKey = "selector";
        private const string NameKey = "name";
        private const string ValueKey = "value";

        private const string GroupsPattern
            = @"(?<selector>(?:(?:[^,{]+)\s*,?\s*)+)\{(?:(?<name>[^}:]+)\s*:\s*(?<value>[^};]+);?\s*)*\}";

        private const string CommentsPattern
            = @"(?<!"")\/\*.+?\*\/(?!"")";

        private readonly Regex _pattern
            = new Regex(GroupsPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

        public CSSParser(string cssString)
        {
            var noCommentsString = Regex.Replace(cssString, CommentsPattern, "");
            var matches = _pattern.Matches(noCommentsString);

            foreach (Match item in matches)
            {
                var selector = item.Groups[SelectorKey].Captures[0].Value.Trim();

                var selectorParts = selector.Split(',').Select(s=>s.Trim());
                foreach(var part in selectorParts)
                {
                    if (!_dict.ContainsKey(part))
                      _dict[part] = new Dictionary<string, string>();
                }

                var classNameCaptures = item.Groups[NameKey].Captures;
                var valueCaptures = item.Groups[ValueKey].Captures;

                var count = item.Groups[NameKey].Captures.Count;

                for (var i = 0; i < count; i++)
                {
                    var className = classNameCaptures[i].Value.TrimIfNotNull();
                    var value = valueCaptures[i].Value.TrimIfNotNull();

                    foreach(var part in selectorParts)
                    {
                        _dict[part][className] = value;
                    }
                }
            }
        }

        public IEnumerable<KeyValuePair<string,string>> LookupValues(string selector)
        {
            IEnumerable<KeyValuePair<string,string>> result
                = new KeyValuePair<string,string>[]{};
            if (_dict.ContainsKey(selector))
            {
                var subdict = _dict[selector];

                result = subdict.ToList();
            }

            return result;
        }

        public string LookupValue(string selector, string style)
        {
            string result = null;
            if (_dict.ContainsKey(selector))
            {
                var subdict = _dict[selector];

                if (subdict.ContainsKey(style))
                    result = subdict[style];
            }

            return result;
        }
    }
}

它可以正常使用这样的输入:

        [TestMethod]
        public void TestParseMultipleElementNames()
        {
          const string css = @"h1, h2, h3, h4, h5, h6
{
    font-family: Georgia, 'Times New Roman', serif;
    color: #006633;
    line-height: 1.2em;
    font-weight: normal;
}
";

          var parser = new CSSParser(css);

          Assert.AreEqual("normal", parser.LookupValue("h4", "font-weight"));
        }

但是当我使用不包含属性的css字符串运行它时:

        [TestMethod]
        public void TestParseNoAttributesStyle()
        {
          const string css = @"
#submenu-container
{
}
";

          var parser = new CSSParser(css);

          Assert.IsFalse(parser.LookupValues("#submenu-container").Any());
        }

该程序挂在CSSParser的这一行:

foreach (Match item in matches)

调试器停止标记当前正在执行的行,永远不会到达循环块本身。

为什么MatchCollection会挂起我的程序?

为了完整性:

namespace Helpers.Extensions
{
  public static class StringExtension
  {
    public static string TrimIfNotNull(this string input)
    {
      return input != null ? input.Trim() : null;
    }
  }
}

3 个答案:

答案 0 :(得分:1)

你的正则表达式效率低下并且燃烧CPU。您可以通过以下方法确认:a)查看使用的CPU时间和b)重复暂停调试器并查看堆栈(将在Regex引擎的内部)。

答案 1 :(得分:1)

据我所知,.net进入一个永恒的循环,因为它尝试了你所拥有的正则表达式的不同方法(GroupsPattern一个) - 我相信它在某个地方犯了一个错误。我已经看过这个正则表达式了,据我所知,你可以轻松地删除\s*中的两个,即分别位于否定组之前的那些[^,{]+[^}:]+他们已经占领了空间。

那就是,而不是:

private const string GroupsPattern = @"(?<selector>(?:(?:[^,{]+)\s*,?\s*)+)\{(?:(?<name>[^}:]+)\s*:\s*(?<value>[^};]+);?\s*)*\}";

我有:

private const string GroupsPattern = @"(?<selector>(?:(?:[^,{]+),?\s*)+)\{(?:(?<name>[^}:]+):\s*(?<value>[^};]+);?\s*)*\}";

现在这是正则表达式,所以我忽视某些东西的机会相当大。另外我相信这也导致一些命名的捕获组可能在它们中有额外的空格(但似乎你无论如何都要修剪它们)。

希望它可用。虽然它仍然需要相当长的时间才能使用你给出的例子。

答案 2 :(得分:0)

我改变了正则表达式:

private const string GroupsPattern
    = @"(?<selector>(?:(?:[^,{]+)\s*,?\s*)+)\{(?:(?<name>[^}:]+)\s*:\s*(?<value>[^};]+);?\s*)*\}";

为:

private const string GroupsPattern
    = @"(?<selector>(?:(?:[^,{]+)\s*,?\s*)+)\{\s*(?:(?<name>[^}:\s]+)\s*:\s*(?<value>[^};]+);?\s*)*\}";

并且执行时间从22秒下降到1毫秒。