“格式错误的”锚标签正则表达式

时间:2017-02-17 20:06:23

标签: regex

我收到了“格式错误”的锚标签(标签没有关闭,没有文字或自动关闭)通过我无法控制的Feed并需要更正它们 - 这里有三个例子:

  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank">(没有结束标记/不自我关闭)
  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank"></a>(无文字)
  • <a class="some-class" href="www.something.com/Resource.PDF" target="_blank"/>(自我关闭)

我正在寻找C#中的正则表达式/正则表达式集合,它将在HTML字符串中找到上述事件。

到目前为止,我有以下内容:

  • (?<anchor><a\s.+?\/{0}>)(?<text>(.*?){0})(<\/a>) ---找到没有文字的主播
  • (?<anchor><a\s.+?\/>) ----找到自我关闭的锚点

我的目标是将这些事件替换为资源作为文本: <a class="some-class" href="www.something.com/Resource.PDF" target="_blank">Resource.PDF</a>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

可能有更好的方法可以做到这一点但是如果有人有类似的问题,我最终通过找到所有锚标签并在需要时纠正它而不是仅查找格式错误的标签来解决这个问题 - 我想出的正则表达式是( https://regex101.com/r/xMnfY8/1): (?<anchor><a\s.*?href=[""'](?<anchorUrl>.+?)[""'].*?>)(?<anchorText>[\s\w]*)(?<anchorClose><\/a>|<|$|\b)

然后我使用C#代码来处理修复标记:

    public string FixAnchorTags(string html)
    {
        var result = html;
        var indexAdjustment = 0;

        foreach (Match match in _anchorTagRegex.Matches(html))
        {
            var anchor = match.Groups["anchor"];
            var anchorUrl = match.Groups["anchorUrl"];
            var anchorText = match.Groups["anchorText"];
            var anchorClose = match.Groups["anchorClose"];                

            if (anchor.Value.EndsWith("/>"))
            {                    
                result = result.Remove(anchor.Index + indexAdjustment, anchor.Length).Insert(anchor.Index + indexAdjustment, anchor.Value.Replace("/>", ">"));
                indexAdjustment -= 1;
            }

            if (string.IsNullOrWhiteSpace(anchorText.Value))
            {
                var fileName = Path.GetFileNameWithoutExtension(anchorUrl.Value);
                result = result.Insert(anchorText.Index + indexAdjustment, fileName);
                indexAdjustment += fileName.Length;
            }

            if (!anchorClose.Value.Matches("</a>"))
            {
                result = result.Insert(anchorClose.Index + indexAdjustment, "</a>");
                indexAdjustment += 4;
            }
        }

        return result;
    }
相关问题