-4

I need a regex for a subdomain but I can't seem to find one and am useless at writing them.

I need a regex to match:

sub1.mydomain.com
sub1.mydomain.local

But not to match:

www.mydomain.com
www.mydomain.local

Or:

[any protocol]//[anysubdomain except www].mydomain.[anysuffix]

Anyone care to take a go at this one?

Update (what I have).

Yes I have just now:

^(?!.*www)[a-z]*(.)?([A-Za-z0-9_-]*)\.([A-Za-z]*)(.*)$

However I need "mydomain.com" to not match.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Paul
  • 1,457
  • 1
  • 19
  • 36
  • 3
    Is there anything you have done to try to solve this problem? We will be more willing to answer your question if you tell us what you have tried so far. (Helpful links for asking better questions: [ask], [FAQ]) – tckmn Apr 27 '13 at 02:32
  • See http://stackoverflow.com/questions/611883/regex-how-to-match-everything-except-a-particular-pattern I think you'll find the answer you're looking for there. – joce Apr 27 '13 at 02:35
  • You will find that my updated regex matches your updated need. – joce Apr 27 '13 at 03:00

1 Answers1

0

The following regex works:

(\w+://)?(?!www)(\w+)\.(\w+)\.(\w+)

so, in C#:

static void Main(string[] args)
{
    var match = Regex.Match("http://sub.blah.com", @"(\w+://)?(?!www)(\w+)\.(\w+)\.(\w+)");
    foreach (var g in match.Groups)
    {
        Console.WriteLine(g);
    }
}

prints

http://sub.blah.com
http://
sub
blah
com

And if you replace "http://sub.blah.com" by "http://www.blah.com" or "www.blah.com" or "blah.com", the program prints nothing (it doesn't find a match). "sub.blah.com" matches however.

joce
  • 9,624
  • 19
  • 56
  • 74