我有一个代码示例,其中 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)
调试器停止标记当前执行的行,循环块本身永远不会到达。
为什么 MatchCollection 会挂起我的程序?
为了完整性:
namespace Helpers.Extensions
{
public static class StringExtension
{
public static string TrimIfNotNull(this string input)
{
return input != null ? input.Trim() : null;
}
}
}