c# - 使纯文本网址可点击的正则表达式字符串问题

标签 c# .net regex url

我需要一个 C# 中的工作 Regex 代码来检测字符串中的纯文本 url (http/https/ftp/ftps) 并通过在其周围放置一个具有相同 url 的 anchor 标记来使它们可点击。我已经制作了一个正则表达式模式,代码附在下面。

但是,如果输入字符串中已经存在任何可点击的 url,则上述代码会在其上放置另一个 anchor 标记。例如,下面代码中的现有子字符串:string sContent: "ftp://www.abc.com'> ftp://www.abc.com "当下面的代码运行时,它上面有另一个 anchor 标记。有什么办法可以解决吗?

        string sContent = "ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc ftp://www.abc.com abbbbb http://www.abc2.com";

        Regex regx = new Regex("(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

        MatchCollection mactches = regx.Matches(sContent);

        foreach (Match match in mactches)
        {
            sContent = sContent.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
        }

另外,我想要一个正则表达式代码,使电子邮件可以通过“mailto”标签点击。我自己可以做,但是上面提到的双 anchor 标签问题也会出现在里面。

最佳答案

我在您的示例测试字符串中注意到,如果重复链接,例如ftp://www.abc.com 在字符串中并且已经链接,那么结果将是双 anchor 链接。您已有的和@stema 提供的正则表达式将起作用,但您需要以不同方式处理如何替换 sContent 变量中的匹配项。

下面的代码示例应该可以满足您的需求:

string sContent = "ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc ftp://www.abc.com abbbbb http://www.abc2.com";

Regex regx = new Regex("(?<!(?:href='|<a[^>]*>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

MatchCollection matches = regx.Matches(sContent);

for (int i = matches.Count - 1; i >= 0 ; i--)
{
    string newURL = "<a href='" + matches[i].Value + "'>" + matches[i].Value + "</a>";

   sContent = sContent.Remove(matches[i].Index, matches[i].Length).Insert(matches[i].Index, newURL);
}

关于c# - 使纯文本网址可点击的正则表达式字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8833588/

相关文章:

c# - 与 ASP.NET Core 的模型绑定(bind)

c# - 变量声明后的一个问号是什么意思?

c# - List、IList和IEnumerable的比较

c++ - 用于使用 ostream 左移语法替换 printf 样式调用的正则表达式

Javascript 使用正则表达式打开文件并读取内容

c# - 最大素因子算法优化

c# - 检查 IP 是否在 LAN 中(在防火墙和路由器后面)

c# - 什么是生活模拟器的好架构

JavaScript 无法识别 Controller

正则表达式最后一个单词从字符串末尾开始