首页 新闻 会员 周边 捐助

正则怎样让文本中的所有网址自动变成连接?

0
悬赏园豆:10 [已解决问题] 解决于 2009-03-27 15:28

比如:我发表一段日志,里面有一段网址或是几段,怎样让显示时直接点地址就能连过去,不借助编辑器之类的。是用正则匹配吗?然后加上<a></a>标签吗?可是正则不会写

问题补充: 怎么样将文本中的网址在显示的时候自动转化为链接
小孤狸的主页 小孤狸 | 初学一级 | 园豆:7
提问于:2009-03-27 12:20
< >
分享
最佳答案
0

by baidu:
public static string ShowUrls(string text)
    {
                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, "<[^>]*>",string.Empty, RegexOptions.Compiled);//清除html标记
        matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        bool flag = true;
        foreach (Match m in matchs)
        {
            string link = "<a href=\"" + m.ToString() + "\" target=\"_new\">" + m.ToString() + "</a>";
            if (linkMatchs.Count > 0)
            {
                foreach (Match linkMatch in linkMatchs)
                {
                    if (linkMatch.Value.IndexOf(m.Value) > -1)
                    {
                        flag = false;
                        break;
                    }
                }
            }           
            if(flag)
            {
                text = text.Replace(m.ToString(), link);
            }
           
        }
        return text;

    }

生鱼片 | 大侠五级 |园豆:5757 | 2009-03-27 12:45
其他回答(1)
0

可以用下面正则来匹配

using System;
using System.Text.RegularExpressions;

public class GeneralValidation
{

    public static bool IsEmail(string Email)
    {
        string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        Regex re = new Regex(strRegex);
        if (re.IsMatch(Email))
            return (true);
        else
            return (false);
    }

    public static bool IsUrl(string Url)
    {
        string strRegex = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
        + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
        + "|" // allows either IP or domain
        + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
        + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // port number- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        Regex re = new Regex(strRegex);

        if (re.IsMatch(Url))
            return (true);
        else
            return (false);
    }
}

eaglet | 园豆:17139 (专家六级) | 2009-03-27 12:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册