I have the following regular expression, which works for a 2 letter subdomain:
var subdomains = [
"es.stackoverflow.com", // valido
"ru.stackoverflow.com", // valido
"12.stackoverflow.com", // invalido
"30.stackkoverflow.com" // invalido
];
const regex = "\^[a-z]{2}.stackoverflow.com$";
for (var i = 0; i < subdomains.length; i++) {
console.log((subdomains[i].match(regex)) ? 'valido' : 'invalido');
}
But I want it to match any subdomain of any length , just letters a to z , nothing else.
This is what I tried:
var subdomains = [
"esssss.stackoverflow.com", // valido
"ru.stackoverflow.com", // valido
"12.stackoverflow.com", // invalido
"30.stackkoverflow.com", // invalido
"es.stackoverflow.com", // valido
"subdominio.stackoverflow.com" // valido
];
const regex = "\^[a-z].stackoverflow.com$";
for (var i = 0; i < subdomains.length; i++) {
console.log((subdomains[i].match(regex)) ? 'valido' : 'invalido');
}
But if I remove the occurrence of N characters {2}
, it doesn't work for me. How can I correct it?
Something to correct before starting:
/
other, without using quotes. That builds directly to a RegExp object .^
with a\
to match the start of the text (it goes directly into the regex).\.
. More info on all special characters: Safe way to escape user input to be processed by regular expressions in JavaScriptSo let's start with the expression:
How to quantify in regex
Quantifiers in regular expressions apply to the previous subpattern. You used it in what you're trying: in
[a-z]{2}
, it{2}
quantizes to[a-z]
(repeats it 2 times).If no quantifier is used, such as in
/^[a-z]\.stackoverflow\.com$/
, then it matches texts that have only 1 character as a subdomain.What you are trying to do is match 1 or more characters in the subdomain. For that, we could use the quantifier
{1,}
(1 to infinities) or, what is the same, the quantifier+
.Code
Other quantifiers
Examples:
Other options for this case
Alternatively, if you wanted it to match case as well, we use the (CASE INSENSITIVE) modifier :
i
Or that it matches, whether or not it has a subdomain, we could group the first part with
(?:
...)
, and make it optional with the quantifier{0,1}
, which is the same as the quantifier?
.more resources