Advanced Regex: Smart auto detect and replace URLs with anchor tags
- by Robert Koritnik
I've written a regular expression that automatically detects URLs in free text that users enter. This is not such a simple task as it may seem at first. Jeff Atwood writes about it in his post.
His regular expression works, but needs extra code after detection is done.
I've managed to write a regular expression that does everything in a single go. This is how it looks like (I've broken it down into separate lines to make it more understandable what it does):
1 (?<outer>\()?
2 (?<scheme>http(?<secure>s)?://)?
3 (?<url>
4 (?(scheme)
5 (?:www\.)?
6 |
7 www\.
8 )
9 [a-z0-9]
10 (?(outer)
11 [-a-z0-9/+&@#/%?=~_()|!:,.;cšžcd]+(?=\))
12 |
13 [-a-z0-9/+&@#/%?=~_()|!:,.;cšžcd]+
14 )
15 )
16 (?<ending>(?(outer)\)))
As you may see, I'm using named capture groups (used later in Regex.Replace()) and I've also included some local characters (cšžcd), that allow our localised URLs to be parsed as well. You can easily omit them if you'd like.
Anyway. Here's what it does (referring to line numbers):
1 - detects if URL starts with open braces (is contained inside braces) and stores it in "outer" named capture group
2 - checks if it starts with URL scheme also detecting whether scheme is SSL or not
3 - start parsing URL itself (will store it in "url" named capture group)
4-8 - if statement that says: if "sheme" was present then www. part is optional, otherwise mandatory for a string to be a link (so this regular expression detects all strings that start with either http or www)
9 - first character after http:// or www. should be either a letter or a number (this can be extended if you'd like to cover even more links, but I've decided not to because I can't think of a link that would start with some obscure character)
10-14 - if statement that says: if "outer" (braces) was present capture everything up to the last closing braces otherwise capture all
15 - closes the named capture group for URL
16 - if open braces were present, capture closing braces as well and store it in "ending" named capture group
First and last line used to have \s* in them as well, so user could also write open braces and put a space inside before pasting link.
Anyway. My code that does link replacement with actual anchor HTML elements looks exactly like this:
value = Regex.Replace(
value,
@"(?<outer>\()?(?<scheme>http(?<secure>s)?://)?(?<url>(?(scheme)(?:www\.)?|www\.)[a-z0-9](?(outer)[-a-z0-9/+&@#/%?=~_()|!:,.;cšžcd]+(?=\))|[-a-z0-9/+&@#/%?=~_()|!:,.;cšžcd]+))(?<ending>(?(outer)\)))",
"${outer}<a href=\"http${secure}://${url}\">http${secure}://${url}</a>${ending}",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
As you can see I'm using named capture groups to replace link with an Anchor tag:
"${outer}<a href=\"http${secure}://${url}\">http${secure}://${url}</a>${ending}"
I could as well omit the http(s) part in anchor display to make links look friendlier, but for now I decided not to.
Question
I would like my links to be replaced with shortenings as well. So when user copies a very long link (for instance if they would copy a link from google maps that usually generates long links) I would like to shorten the visible part of the anchor tag. Link would work, but visible part of an anchor tag would be shortened to some number of characters. I could as well append ellipsis at the end of at all possible (and make things even more perfect).
Does Regex.Replace() method support replacement notations so that I can still use a single call? Something similar as string.Format() method does when you'd like to format values in string format (decimals, dates etc...).