1

请帮助我使用 C# .netRegex Replace方法从此处替换所有其他 Facebook 信息。

例子

<a href="/l.php?u=http%3A%2F%2Fon.fb.me%2FOE6gnB&amp;h=yAQFjL0pt&amp;s=1" target="_blank" rel="nofollow nofollow" onmouseover="LinkshimAsyncLink.swap(this, &quot;http:\/\/on.fb.me\/OE6gnB&quot;);" onclick="LinkshimAsyncLink.swap(this, &quot;\/l.php?u=http\u00253A\u00252F\u00252Fon.fb.me\u00252FOE6gnB&amp;h=yAQFjL0pt&amp;s=1&quot;);">http://on.fb.me/OE6gnB</a>somehtml

输出

somehtml <a href="http://on.fb.me/OE6gnB">on.fb.me/OE6gnB</a> somehtml

我尝试遵循正则表达式,但它们对我不起作用

searchPattern = "<a([.]*)?/l.php([.]*)?(\">)?([.]*)?(</a>)?";
replacePattern = "<a href=\"$3\" target=\"_blank\">$3</a>";

谢谢

4

2 回答 2

2

我设法使用带有以下代码的正则表达式来做到这一点

 searchPattern = "<a(.*?)href=\"/l.php...(.*?)&amp;?(.*?)>(.*?)</a>";
          string html1 = Regex.Replace(html, searchPattern, delegate(Match oMatch)
    {
        return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", HttpUtility.UrlDecode(oMatch.Groups[2].Value), oMatch.Groups[4].Value);

    });
于 2012-09-05T10:25:48.420 回答
1

你可以试试这个(必须添加 System.Web 才能使用System.Web.HttpUtility):

        string input = @"<a href=""/l.php?u=http%3A%2F%2Fon.fb.me%2FOE6gnB&amp;h=yAQFjL0pt&amp;s=1"" target=""_blank"" rel=""nofollow nofollow"" onmouseover=""LinkshimAsyncLink.swap(this, &quot;http:\/\/on.fb.me\/OE6gnB&quot;);"" onclick=""LinkshimAsyncLink.swap(this, &quot;\/l.php?u=http\u00253A\u00252F\u00252Fon.fb.me\u00252FOE6gnB&amp;h=yAQFjL0pt&amp;s=1&quot;);"">http://on.fb.me/OE6gnB</a>somehtml";
        string rootedInput = String.Format("<root>{0}</root>", input);
        XDocument doc = XDocument.Parse(rootedInput, LoadOptions.PreserveWhitespace);

        string href;
        var anchors = doc.Descendants("a").ToArray();
        for (int i = anchors.Count() - 1; i >= 0;  i--)
        {
            href = HttpUtility.ParseQueryString(anchors[i].Attribute("href").Value)[0];

            XElement newAnchor = new XElement("a");
            newAnchor.SetAttributeValue("href", href);
            newAnchor.SetValue(href.Replace(@"http://", String.Empty));

            anchors[i].ReplaceWith(newAnchor);
        }
        string output = doc.Root.ToString(SaveOptions.DisableFormatting)
                        .Replace("<root>", String.Empty)
                        .Replace("</root>", String.Empty);
于 2012-08-14T08:31:31.377 回答