我正在使用Twitter API,并希望将所有URL转换为超链接。
你想到的最有效的方法是什么?
来自:
string myString = "This is my tweet check it out http://tinyurl.com/blah";
This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>
我正在使用Twitter API,并希望将所有URL转换为超链接。
你想到的最有效的方法是什么?
来自:
string myString = "This is my tweet check it out http://tinyurl.com/blah";
This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>
正则表达式可能是您在此类任务中的好帮手:
Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "<a href=\"$1\">$1</a>");
匹配URL的正则表达式可能需要一些修改。
(https?://[^ ]+)
,因为https并不那么罕见。 - John Leidegren我曾经使用jQuery消费JSON API来完成这个完全相同的事情,以下是linkify函数:
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
这实际上是一个麻烦的问题。URL可以包含(并以)标点符号结尾,所以在普通文本中嵌入URL时很难确定URL的实际结尾。例如:
http://example.com/.
这是一个有效的URL,但它也可能只是一句话的结尾。
I buy all my witty T-shirts from http://example.com/.
find more on http://www.stackoverflow.com现在尝试这段代码
private void ModifyString()
{
string input = "find more on http://www.authorcode.com ";
Regex regx = new Regex(@"\b((http|https|ftp|mailto)://)?(www.)+[\w-]+(/[\w- ./?%&=]*)?");
string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));
}
static string ReplaceURl(Match m)
{
string x = m.ToString();
x = "< a href=\"" + x + "\">" + x + "</a>";
return x;
}
/cheer for RedWolves
来自:this.replace(/ [A-Za-z] +:\/\/ [A-Za-z0-9- ] +。[A-Za-z0-9- :%& \?/。=] + /,function(m){...
请参阅:/ [A-Za-z] +:\/\/ [A-Za-z0-9- ] +。[A-Za-z0-9- :%& \?/。=] + /
这是用于地址“anyprotocol”://“anysubdomain / domain”。“anydomainextension和address”的代码,
它是其他字符串操作的完美示例。您可以使用.replace随意切割并插入所需的适当“a href”。
我使用jQuery轻松更改这些链接的属性为“target = _blank”,即使.link方法不允许您自定义它们。
我个人喜欢在字符串对象上附加自定义方法以进行即时字符串过滤(String.prototype.linkify声明),但我不确定在需要组织10多个自定义linkify类似函数的大规模环境中会发生什么。我认为在那一点上,您肯定必须对代码结构做出其他处理。
也许一位兽医会偶然路过这里并启发我们。