tags:

views:

196

answers:

4

In my ASP.NET application, I want to use regular expressions to change URLs into hyper links in user posts, for example:

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

to

<a href="http://www.somesite.com/default.aspx"&gt;http://www.somesite.com/default.aspx&lt;/a&gt;

This is fairly easy using Regex.Replace(), but the problem I'm having is that I want to truncate the link text if the URL is too long, for example:

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

to

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

so that it displays like this:

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

I tried to use Regex.Matches() but I don't know how to replace the text, any suggestions?

Thanks for your help ...

Edit:
Never mind guys, I figured it out on my own, it turned out to be incredibly simple, I just used a MatchEvaluator!

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

+5  A: 

This is an example of where JUST using a Regex is trying to do too much. I would recommend using Regex to FIND the patterns, but use code logic to adjust the output to your liking. It's not too hard to output the new pattern with replacements, but trying to control the length of the link text is pushing too far.

Michael Bray
A: 

AFAIK there is no out-of-the-box support for this. You will indeed have to iterate through the Regex.Matches() yourself and do the replacement yourself (via string.Replace or a StringBuilder), truncating the text where needed.

Vilx-
A: 

You can accomplish the accomplish the conversion by checking for the hyperlinks (via regex) and then do something like this...

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

Jeff's post on doing this for SO is quite enlightening, not as easy as it looks:

http://www.codinghorror.com/blog/archives/001181.html

Kev