For example there are URLs http://www.subdomain1.domain.com.uk and http://www.subdomain2.domain.uk, from these URLs I need to extract only the name subdomain1 and subdomain2 accordingly.

But if I receive http://www.subdomain3.co.uk or http://www.subdomain4.com I need to get the whole URL like subdomain3.co.uk and subdomain4.com.

My expression catches whole URL: ^http:\/\/(?:www\.)?((?!SubdomainToNegate|www)[^\.]*\.(?!domain\.com\.uk|domain\.uk).*)$

My situation is shown better over there: http://www.rubular.com/r/qAdMdJoNYb