public static string FixCategories(string articleText)
{
CategoryStart = @"[[" + (Variables.Namespaces.ContainsKey(Namespace.Category) ? Variables.Namespaces[Namespace.Category] : "Category:");
// Performance: only need to apply changes to portion of article containing categories
Match cq = WikiRegexes.CategoryQuick.Match(articleText);
if (cq.Success)
{
// Allow some characters before category start in case of excess opening braces
int cutoff = Math.Max(0, cq.Index-2);
string cats = articleText.Substring(cutoff);
string catsOriginal = cats;
// fix extra brackets: three or more at end
cats = Regex.Replace(cats, @"(" + Regex.Escape(CategoryStart) + @"[^\r\n\[\]{}<>]+\]\])\]+", "$1");
// three or more at start
cats = Regex.Replace(cats, @"\[+(?=" + Regex.Escape(CategoryStart) + @"[^\r\n\[\]{}<>]+\]\])", "");
cats = WikiRegexes.LooseCategory.Replace(cats, LooseCategoryME);
// Performance: return original text if no changes
if (cats.Equals(catsOriginal))
return articleText;
articleText = articleText.Substring(0, cutoff) + cats;
}
return articleText;
}