正则表达式将URL转换为.Net中的超链接

时间:2009-01-01 00:35:11

标签: .net regex

在我的ASP.NET应用程序中,我想使用正则表达式将URL更改为用户帖子中的超链接,例如:

http://www.somesite.com/default.aspx   

<a href="http://www.somesite.com/default.aspx">http://www.somesite.com/default.aspx</a>

使用Regex.Replace()相当容易,但我遇到的问题是,如果URL太长,我想截断链接文本,例如:

http://www.somesite.com/files/default.aspx?id=a78b38ae723b1f8ed232c23de7f9121d&n=93b34a732e074c934e32d123de19c83d

<a href="http://www.somesite.com/files/default.aspx?id=a78b38ae723b1f8ed232c23de7f9121d&n=93b34a732e074c934e32d123de19c83d">http://www.somesite.com/files/default.aspx?id=a78b38ae723b1f8...</a>

以便它显示如下:

http://www.somesite.com/files/default.aspx?id=a78b38ae723b1f8...

我尝试使用Regex.Matches()但我不知道如何替换文本,有什么建议吗?

感谢您的帮助......

编辑: 别介意我,我自己想出来,结果非常简单,我刚用了MatchEvaluator

public static string Replace(
    string input,
    string pattern,
    MatchEvaluator evaluator
)

3 个答案:

答案 0 :(得分:5)

这是JUST using a Regex is trying to do too much的示例。我建议使用Regex来查找模式,但是使用代码逻辑来根据自己的喜好调整输出。用替换输出新模式并不太难,但试图控制链接文本的长度太过分了。

答案 1 :(得分:0)

AFAIK没有开箱即用的支持。您确实必须自己遍历Regex.Matches()并自己进行替换(通过string.Replace或StringBuilder),在需要的地方截断文本。

答案 2 :(得分:0)

您可以通过检查超链接(通过正则表达式)完成转换,然后执行类似的操作......

string displayText = url.Substring(0, maxLength);
string hyperlink = string.Format("<a href=\"{0}\">{1}</a>", url, displayText);