c# - 用于转换超链接的 RegExp 帮助

标签 c# regex url

我试图想出一个正则表达式并尝试了许多组合并搜索以找到将非超链接地址转换为超链接的解决方案。

http://twitpic.com/abcdef http://www.smh.com.au askjhsd www.hotmail.com ks sd 
<a href="http://www.aaaaaaaa.com">aaaaaaaa</a>

我想要 http://twitpic.com/abcdef , http://www.smh.com.auwww.hotmail.com被拾起但不是http://www.aaaaaaaa.com因为它包裹在 <a> 周围已经标记。

我目前在 C# 中使用这个正则表达式

return Regex.Replace(input, @"(\b((http|https)://|www\.)[^ ]+\b)", 
   @" <a href=""$0"" target=""_blank"">$0</a>", RegexOptions.IgnoreCase);

我不知道如何让它排除已经包含在 <a> 中的内容或 <img>

帮助:)

编辑

对于那些稍后阅读本文的人,这是我想出的最终解决方案

/// <summary>
/// Adds to the input string a target=_blank in the hyperlinks
/// </summary>
public static string ConvertURLsToHyperlinks(string input)
{
    if (!string.IsNullOrEmpty(input))
    {
        var reg = new Regex(@"(?<!<\s*(?:a|img)\b[^<]*)(\b((http|https)://|www\.)[^ ]+\b)");
        return reg.Replace(input, new MatchEvaluator(ConvertUrlsMatchDelegate));

    }
    return input;
}

public static string ConvertUrlsMatchDelegate(Match m)
{
    // add in additional http:// in front of the www. for the hyperlinks
    var additional = "";
    if (m.Value.StartsWith("www."))
    {
        additional = "http://";
    }
    return "<a href=\"" + additional + m.Value + "\" target=\"_blank\">" + m.Value + "</a>";
}

最佳答案

你可以使用

@"(?<!<\s*(?:a|img)\b[^<]*)(\b((http|https)://|www\.)[^ ]+\b)"

作为你的正则表达式。 negative lookbehind assertion .

lookbehind 断言解释:

(?<!       # Assert that it's impossible to match before the current position:...
 <         # a <
 \s*       # optional whitespace
 (?:a|img) # a or img
 \b        # as an entire word
 [^<]*     # followed by any number of characters except <
)          # end of lookbehind

关于c# - 用于转换超链接的 RegExp 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013783/

相关文章:

javascript - 在javascript中替换的正则表达式

javascript - 使用 JavaScript 匹配精确的字符串

PHP 从 URL 获取结果

c# - LINQ 在选择字典属性时创建新的匿名类型

c# - PayPal 400 Bad Request,更具体?

javascript - 使用 switch 语句评估 javascript 中的正则表达式

windows - bat文件打开带有参数的网页到本地文件

c# - 如何使用 Bouncy CaSTLe 或其他 C# 库在 C# 中验证此 PGP 消息

c# - 为什么像 BindingList 或 ObservableCollection 这样的类不是线程安全的?

javascript - 我的 javascript 代码在同一窗口中打开包含输入值的 url 有什么问题吗?