El problema con la expresión regular anterior es: si usted no sabe lo que es el protocolo, o lo que es el sufijo de dominio, obtendrá algunos resultados inesperados. Aquí hay un poco de cuentas Regex para esas situaciones. : D
/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i //javascript
Esto siempre debe devolver el subdominio (si está presente) en el grupo 1. Aquí está en un ejemplo de JavaScript, pero también debería funcionar para cualquier otro motor que apoya las afirmaciones de preanálisis positivos:
// EXAMPLE of use
var regex = /(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i
, whoKnowsWhatItCouldBe = [
"www.mydomain.com/whatever/my-site" //matches: www
, "mydomain.com"// does not match
, "http://mydomain.com" // does not match
, "https://mydomain.com"// does not match
, "banana.com/somethingelse" // does not match
, "https://banana.com/somethingelse.org" // does not match
, "http://what-ever.mydomain.mu" //matches: what-ever
, "dev-www.thisdomain.com/whatever" // matches: dev-www
, "hot-MamaSitas.SomE_doma-in.au.xxx"//matches: hot-MamaSitas
, "http://hot-MamaSitas.SomE_doma-in.au.xxx" // matches: hot-MamaSitas
, "пуст.пустыня.ru" //even non english chars! Woohoo! matches: пуст
, "пустыня.ru" //does not match
];
// Run a loop and test it out.
for (var i = 0, length = whoKnowsWhatItCouldBe.length; i < length; i++){
var result = whoKnowsWhatItCouldBe[i].match(regex);
if(result != null){
// YAY! We have a match!
} else {
// Boo... No subdomain was found
}
}
¿Está permitido el subdominio? –
Sí, puede tener string.string.domain.gtld –