tags:

views:

49

answers:

2

Hi All,

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 become production code.

I would like to write a class which converts any of these URLs,

  1. www.google.co.nz
  2. WWW.google.co.nz
  3. google.co.nz
  4. 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.

+2  A: 

Be very careful:

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

John at CashCommons
I just want to demo that you can write unit tests, and then decide to refactor your code, so I don't need anything that is perfect
peter
It sounds you just need something that works. If what you wrote in your question works for what you need, then you're done. My answer was just a warning that URLs have a number of gotchas, and the general case of a URL has a lot of characters you wouldn't expect. (I didn't expect them, anyway.)
John at CashCommons
A: 

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.

Einar Egilsson
Perfect. Thanks.
peter