正则表达式:替换URL,除非以src =开头

时间:2011-10-18 07:59:42

标签: c# .net regex

我正在寻找一个在Refex.Replace中使用的正则表达式,它允许我附加一个带链接元素的url。 这个想法是这样的:

http://www.tenforce.com => <a target='new' href='http://www.tenforce.com'>http://www.tenforce.com</a>

但是,当URL是html元素的一部分时,不允许正则表达式执行此操作,例如对于图像标记。所以如果我们有例如:

<img src="http://www.tenforce.com/logo.jpg" />

不应使用正则表达式进行转换。

我们使用的原始正则表达式就是这个:

@"(http|ftp|https):((\/\/)|(\\\\))[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?";

但是这会将它可以找到的每个网址编码到一个标签中。当它们以src = \“

为前缀时,我不希望它对url进行编码

所以我尝试添加 [^(src =。)] ,但这会导致正常的网址不再被转换。但它不会转换图像标签。

代码如下所示:

/// <summary>
        /// Extends the text with hyperlinks.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="workspaceId">The workspace id where the user is working in. Used when parsing the wiki links</param>
        /// <returns></returns>
        public static string ExtendWithHyperlinks(string value, int? workspaceId)
        {
            if (value == null) return null;

            const string UrlPattern = @"[^(src=.)](http|ftp|https):((\/\/)|(\\\\))[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?";
            const string FilePattern = @"(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\\w((\.*\w+)|( *\w+))*)+";

            value = Regex.Replace(value, UrlPattern, "<a target='new' href='$0'>$0</a>").Replace(":\\\\", "://");
            value = Regex.Replace(value, FilePattern, "<a target='new' href='file:///$0'>$0</a>");
            value = TemplateParser.Parse(value, workspaceId, Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Remove(0, 8))));
            return value;
        }

2 个答案:

答案 0 :(得分:1)

你可以用负面的背后隐藏

来做
(?<!src=['"]?)(http|ftp|https):...

答案 1 :(得分:0)

实际上,这个问题是SO上许多其他人的骗局。真正的答案是:don't use Regex to deal with HTML/XML。使用专用的HTML解析器。 HtmlAgilityPack非常棒,你不必使用不适合这项工作的工具来填补它。

相关问题