Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding http:// to all links without a protocol

Tags:

regex

vb.net

I use VB.NET and would like to add http:// to all links that doesn't already start with http://, https://, ftp:// and so on.

"I want to add http here <a href=""www.google.com"" target=""_blank"">Google</a>,
but not here <a href=""http://www.google.com"" target=""_blank"">Google</a>."

It was easy when I just had the links, but I can't find a good solution for an entire string containing multiple links. I guess RegEx is the way to go, but I wouldn't even know where to start.

I can find the RegEx myself, it's the parsing and prepending I'm having problems with. Could anyone give me an example with Regex.Replace() in C# or VB.NET?

Any help appreciated!

like image 868
Magnus Engdal Avatar asked Jan 23 '26 06:01

Magnus Engdal


1 Answers

Quote RFC 1738:

"Scheme names consist of a sequence of characters. The lower case letters "a"--"z", digits, and the characters plus ("+"), period ("."), and hyphen ("-") are allowed. For resiliency, programs interpreting URLs should treat upper case letters as equivalent to lower case in scheme names (e.g., allow "HTTP" as well as "http")."

Excellent! A regex to match:

/^[a-zA-Z0-9+.-]+:\/\//

If that matches your href string, continue on. If not, prepend "http://". Remaining sanity checks are yours unless you ask for specific details. Do note the other commenters' thoughts about relative links.


EDIT: I'm starting to suspect that you've asked the wrong question... that you perhaps don't have anything that splits the text up into the individual tokens you need to handle it. See Looking for C# HTML parser


EDIT: As a blind try at ignoring all and just attacking the text, using case insensitive matching,

/(<a +href *= *")(.*?)(" *>)/

If the second back-reference matches /^[a-zA-Z0-9+.-]+:\/\//, do nothing. If it does not match, replace it with

$1 + "http://" + $2 + $3

This isn't C# syntax, but it should translate across without too much effort.

like image 167
Jeff Ferland Avatar answered Jan 26 '26 21:01

Jeff Ferland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!