public ReferenceReplacer(string text, ref ReferenceCollection references, ReferenceOrder order) { _usedReferences = new ReferenceCollection(); _badIds = new HashSet<string>(); _unknownIds = new HashSet<int>(); _unknownTags = new HashSet<string>(); _replacements = new Dictionary<string, Reference[]>(); var re = new Regex(@"\[\[(([" + RefIdPrefix + @"\d\w\s" + RefDelimiter + @"]+)?)\]\]", RegexOptions.IgnoreCase); foreach (Match match in re.Matches(text)) { var refText = match.Groups[0].Captures[0].Value; var refList = match.Groups[1].Captures[0].Value; if (_replacements.ContainsKey(refText)) continue; var parts = refList.Split(new[] {RefDelimiter}, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 1) { // Replacements with no references supposed to be deleted from document _replacements.Add(refText, null); continue; } var refs = new HashSet<Reference>(); foreach (var part in parts.Select(part => part.Trim()).Where(p => p.Length != 0)) { Reference reference; if (part[0] == '#') { int id; if (!Int32.TryParse(part.Substring(1), NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out id)) { _badIds.Add(part); continue; } reference = references.GetById(id); if (reference == null) { _unknownIds.Add(id); continue; } } else { reference = references.GetByTag(part); if (reference == null) { _unknownTags.Add(part); continue; } } refs.Add(reference); if (!_usedReferences.Contains(reference)) { _usedReferences.Add(reference); } } _replacements.Add(refText, refs.ToArray()); } _usedReferences.Sort(order); for (var i = 0; i < _usedReferences.Count; i++) { _usedReferences[i].RefNum = i + 1; } }