Method to convert URLs - would a Regex be appropriate
Just wondering if you had any thoughts on this problem. I want to make it clear that this is for a coding DEMO. So this code is not ever going to becom开发者_如何学Ce production code.
I would like to write a class which converts any of these URLs,
- www.google.co.nz
- WWW.google.co.nz
- google.co.nz
- http://google.co.nz
to this,
http://www.google.co.nz
So it should be ignoring what is on the start and concatinating http://www.
How would you suggest I do that? I have some logic which says stuff like this,
if (address.ToLower().Contains("http://"))
{
address = address.ToLower().Replace("http://", "");
}
if (address.ToLower().Contains("www."))
{
address = address.ToLower().Replace("www.", "");
}
address.Append("http://www.");
Any thoughts? How else could I solve this problem? Is there a regex that would help? Or would you solve it like I have above?
By the way this code is for a demo, so don't ask why I would want this class.
The code you have now doesn't handle https:// correctly and mangles urls that have www. in the middle of them (unlikely but possible). I would do it something like:
string prefix = url.ToLower().StartsWith("https://") ? "https://www." : "http://www.";
url = Regex.Replace(url, @"^((https?://)?(www\.)?)", prefix, RegexOptions.IgnoreCase);
It is certainly possible to do it all in a single regular expression operation, but readability might suffer. And of course you should do the usual checking for string.IsNullOrEmpty etc.
The System.Uri class might also have some interesting stuff you could use for this.
精彩评论