c# - MatchCollection 可以在尝试迭代时挂起程序吗?

标签 c# regex

我有一个代码示例,其中 MatchCollection 似乎在尝试将其与 foreach 一起使用时挂起程序。

我正在使用类 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)

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

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

为了完整性:

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

最佳答案

您的 Regex 效率低下并且正在消耗 CPU。您可以通过 a) 查看使用的 CPU 时间和 b) 反复暂停调试器并查看堆栈(将在 Regex 引擎的内部)来确认这一点。

关于c# - MatchCollection 可以在尝试迭代时挂起程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016524/

相关文章:

java - 如何在java中分析一个字符串以确保它既有字母又有数字?

C# 日期时间操作

c# - 我如何遍历 OracleDataReader 的所有列

c# - .RemoveRange 在 Entity Framework 中不首先获取数据库记录

javascript - 用于检查用户代理字符串中是否存在关键字的正则表达式

C# RegEx.Split 分隔符后跟特定单词

c# - 在不同类型上调用相同的方法

c# - 在 WPF 控件 C# 中嵌入 Google map

python - 匹配由另一个正则表达式分隔的所有内容?

java - 匹配多语言数字的正则表达式不检测中文数字