将 URL 转换为 C# 字符串中超链接的最简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:12:27  来源:igfitidea点击:

Easiest way to convert a URL to a hyperlink in a C# string?

提问by Nathan Birkes

I am consuming the Twitter API and want to convert all URLs to hyperlinks.

我正在使用 Twitter API 并希望将所有 URL 转换为超链接。

What is the most effective way you've come up with to do this?

你想出的最有效的方法是什么?

from

string myString = "This is my tweet check it out http://tinyurl.com/blah";

to

This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>

采纳答案by samjudson

Regular expressions are probably your friend for this kind of task:

对于此类任务,正则表达式可能是您的朋友:

Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "<a href=\"\"></a>");

The regular expression for matching URLs might need a bit of work.

匹配 URL 的正则表达式可能需要一些工作。

回答by Derek Park

This is actually an ugly problem. URLs can contain (and end with) punctuation, so it can be difficult to determine where a URL actually ends, when it's embedded in normal text. For example:

这实际上是一个丑陋的问题。URL 可以包含(并以)标点符号,因此当它嵌入到普通文本中时,很难确定 URL 的实际结束位置。例如:

http://example.com/.

is a valid URL, but it could just as easily be the end of a sentence:

是一个有效的 URL,但它也可以很容易地作为句子的结尾:

I buy all my witty T-shirts from http://example.com/.

You can't simply parse until a space is found, because then you'll keep the period as part of the URL. You also can't simply parse until a period or a space is found, because periods are extremely common in URLs.

在找到空格之前您不能简单地解析,因为那样您会将句点保留为 URL 的一部分。您也不能在找到句点或空格之前简单地进行解析,因为句点在 URL 中极为常见。

Yes, regex is your friend here, but constructing the appropriate regex is the hard part.

是的,正则表达式在这里是您的朋友,但构建适当的正则表达式是困难的部分。

Check out this as well: Expanding URLs with Regex in .NET.

也请查看:在 .NET 中使用正则表达式扩展 URL

回答by RedWolves

I did this exact same thing with jquery consuming the JSON APIhere is the linkify function:

我对使用 JSON API 的 jquery做了同样的事情,这里是 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);
    });
 };

回答by winfred

/cheer for RedWolves

/为红狼加油

from: this.replace(/[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/, function(m){...

see: /[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/

来自:this.replace(/[A-Za-z]+://[A-Za-z0-9- ]+.[A-Za-z0-9-:%&\?/.=]+/ , 函数(m){...

见:/[A-Za-z]+://[A-Za-z0-9- ]+.[A-Za-z0-9-:%&\?/.=]+/

There's the code for the addresses "anyprotocol"://"anysubdomain/domain"."anydomainextension and address",

有地址“anyprotocol”://“anysubdomain/domain”的代码。“anydomainextension and address”,

and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper "a href"s where needed.

这是字符串操作其他用途的完美示例。您可以使用 .replace 随意切片和切块,并在需要的地方插入适当的“a href”。

I used jQuery to change the attributes of these links to "target=_blank" easily in my content-loading logic even though the .link method doesn't let you customize them.

我使用 jQuery 在我的内容加载逻辑中轻松地将这些链接的属性更改为“target=_blank”,即使 .link 方法不允许您自定义它们。

I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.

我个人喜欢将自定义方法添加到字符串对象以进行动态字符串过滤(String.prototype.linkify 声明),但我不确定这在大型环境中会如何发挥作用必须组织 10 多个自定义的类似链接的功能。我认为此时您肯定必须对您的代码结构做一些其他的事情。

Maybe a vet will stumble along here and enlighten us.

也许兽医会在这里绊倒并启发我们。

回答by herry

You can add some more control on this by using MatchEvaluator delegate function with regular expression: suppose i have this string:

您可以通过使用带有正则表达式的 MatchEvaluator 委托函数对此添加更多控制:假设我有这个字符串:

find more on http://www.stackoverflow.com 

now try this code

现在试试这个代码

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;
}