Mam przykład kodu, w którym MatchCollection wydaje się zawiesić program podczas próby użycia go z foreach.Czy MatchCollection może zawiesić program podczas próby iteracji?
ja parsowania css za pomocą klasy CSSParser:
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;
}
}
}
i współpracuje z wejściem jak ten:
[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"));
}
ale gdy uruchomię go z ciągiem css nie zawierające atrybuty:
[TestMethod]
public void TestParseNoAttributesStyle()
{
const string css = @"
#submenu-container
{
}
";
var parser = new CSSParser(css);
Assert.IsFalse(parser.LookupValues("#submenu-container").Any());
}
program wisi na tej linii w CSSParser:
foreach (Match item in matches)
Debuger przestaje oznaczać aktualnie uruchomioną linię, sam blok pętli nigdy nie zostanie osiągnięty.
Dlaczego MatchCollection zawiesza się w moim programie?
Dla kompletności:
namespace Helpers.Extensions
{
public static class StringExtension
{
public static string TrimIfNotNull(this string input)
{
return input != null ? input.Trim() : null;
}
}
}
Nie jestem ekspertem od Regex, ale silnik Regex może utknąć lub zająć dużo czasu, jeśli ma wykonywać operacje z wyprzedzeniem i lookbehind. Projektowanie Regex w celu zminimalizowania tych pomoże. Być może ekspert Regex może ci pomóc w szczegółach. +1 =] – Sean
Zatrzymaj debugger i spójrz na stos, aby ustalić, co się dzieje.Zaznacz "Pokaż kod zewnętrzny", aby zobaczyć wszystko. – usr
a) Języki takie jak ten nie powinny * naprawdę * być przetwarzane przez Regex. b) dlaczego nie [użyć czegoś od ręki] (http://stackoverflow.com/q/512720/50776)? Prawdopodobnie będzie to znacznie szybsze i bardziej niezawodne i pozwoli Ci osiągnąć więcej w swoim projekcie niż zrobić to ręcznie. – casperOne