Il problema con la regex di cui sopra è: se non si sa che cosa il protocollo è, o ciò che il suffisso di dominio è, si ottengono alcuni risultati inaspettati. Ecco alcuni account regex per quelle situazioni. : D
/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i //javascript
Questo dovrebbe sempre restituire il sottodominio (se presente) nel gruppo 1. Qui è in un esempio di Javascript, ma dovrebbe funzionare anche per qualsiasi altro motore che supporta positive affermazioni look-ahead:
// 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
}
}
È consentito il sottotubo? –
Sì, si può avere string.string.domain.gtld –