日期:2014-05-20  浏览次数:20393 次

http开头的字符串如何自动加上连接
一个文本框里提交的内容   如果有HTTP开头的字符串就自动加上链接
但是还要判断两种情况

1: <a   href= "http字符串 "> ... </a>

2: <a   href= "... "> http字符串 </a>

以上两种情况就不用自动加上连接拉

也就是说只检查没有设置连接的   HTTP开头的字符串

可能要用到正则表达式   请大家指点



------解决方案--------------------

------解决方案--------------------
string strContent = txtKey.Value; //


//Regex emailregex = new Regex(@ "([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+) ", RegexOptions.IgnoreCase| RegexOptions.Compiled);

Regex re = new Regex(@ " <a[^> ]+href=\s*(?: '(? <href> [^ ']+) '| " "(? <href> [^ " "]+) " "|(? <href> [^> \s]+))\s*[^> ]*> (? <text> .*?) </a> ", RegexOptions.IgnoreCase |RegexOptions.Singleline);
if (!re.IsMatch(strContent))
{
Regex urlregex = new Regex(@ "(http:\/\/([\w.]+\/?)\S*) ", RegexOptions.IgnoreCase| RegexOptions.Compiled);
if (urlregex.IsMatch(strContent))
{
strContent = " <a href=\ " "+ strContent + "\ " target=\ "_blank\ "> "+ strContent + " </a> ";
}
}


Response.Write(strContent);
------解决方案--------------------
楼上的不知道能用吗?
------解决方案--------------------
呵呵 刚才在vs2003下 建了个测试了下
应该没问题。。。

------解决方案--------------------
string strContent = txtKey.Value;


//Regex emailregex = new Regex(@ "([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+) ", RegexOptions.IgnoreCase| RegexOptions.Compiled);

Regex re = new Regex(@ " <a[^> ]+href=\s*(?: '(? <href> [^ ']+) '| " "(? <href> [^ " "]+) " "|(? <href> [^> \s]+))\s*[^> ]*> (? <text> .*?) </a> ", RegexOptions.IgnoreCase |RegexOptions.Singleline);

if (!re.IsMatch(strContent))
{
Regex urlregex = new Regex(@ "(http:\/\/([\w.]+\/?)\S*) ", RegexOptions.IgnoreCase| RegexOptions.Compiled);
if (urlregex.IsMatch(strContent))
{
Match em = urlregex.Match(strContent);
string st = strContent.Substring(em.Index, em.Length);

strContent = strContent.Replace(st, " <a href=\ " "+ st + "\ " target=\ "_blank\ "> "+ st + " </a> ");
//st = " <a href=\ " "+ st + "\ " target=\ "_blank\ "> "+ st + " </a> ";
}
}
Response.Write(strContent);
------解决方案--------------------
楼主可以把可能出现的情况具体说下
1: <a href= "http字符串 "> ... </a>
2: <a href= "... "> http字符串 </a>
这两种情况下“href=”后一定是“ "”吗

需要加链接的 HTTP开头的字符串以什么为结束标志,空格吗,如果是这样,完全可以写进一个正则表达式的
yourStr = .................;
string resultStr = Regex.Replace(yourStr, @ "(? <!(( <a\s+href([\s\S]*?)> )|( <a\s+href= " ")))(http([^\s <]*)) ",@ " <a href= " "$5 " " target= " "_blank " "> $5 </a> ",RegexOptions.IgnoreCase);

------解决方案--------------------
改造了一下,楼主试下
yourStr = ...............;