将地址转换为链接的正则表达式(regex url href)

将文章内容中没有链接的地址转换为链接。
代码如下:
    public static string ShowUrls(string text)
    
{
        
//代码来自博客园 http://www.cnblogs.com
        Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]*))",
            RegexOptions.IgnoreCase | RegexOptions.Compiled);        
        MatchCollection linkMatchs 
= linkRegex.Matches(text);
        
        
string pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])";
        MatchCollection matchs;

        
string clearText = Regex.Replace(text, "(<br>|<br/>)"," ", RegexOptions.IgnoreCase);
        clearText 
= Regex.Replace(clearText, "<[^>]*>"string.Empty, RegexOptions.Compiled);//清除html标记
        matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        
bool flag1 = true;
        
        
for(int i=0;i<matchs.Count;i++)
        
{
            Match m 
= matchs[i];
            
string link = "<a href=\"" + m.ToString() + "\" target=\"_blank\">" + m.ToString() + "</a>";
            
if (linkMatchs.Count > 0)
            
{
                
foreach (Match linkMatch in linkMatchs)
                
{
                    
if (linkMatch.Value.IndexOf(m.Value) > -1)
                    
{
                        flag1 
= false;
                        
break;
                    }

                }

            }
            
            
if(flag1)
            
{
                
bool flag2 = true;
                
for (int j = 0; j < i; j++)
                
{
                    
if (m.ToString() == matchs[j].ToString())
                    
{
                        flag2 
= false;
                    }

                }

                
if (flag2)
                
{
                    text 
= text.Replace(m.ToString(), link);
                }

            }

            
        }

        
return text;
    }

posted @   dudu  阅读(3806)  评论(3编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2006-12-19 [功能改进]通过Blog客户端直接发随笔至网站分类
2006-12-19 调整一下工作的节奏
2005-12-19 Software Update Services Server使用经验
2004-12-19 博客园新增镜像站点
2004-12-19 [新功能]修改发表过的评论
点击右上角即可分享
微信分享提示