If it’s to limit a number the easiest would be:
if ($numero > 0 && $numero <= 1000) {
//Algo aqui é executado
}
It has to be greater than zero and less than or equal to 1000.
You don’t need regex for something so simple, now if the goal is actually to apply the regex to another "group" need to analyze what you really want and which string you want to match/marry, because I can give a regex response that will actually break the logic of your current regex that already exists.
Something that would be the basic to work with regex, of which I I can’t guarantee that will break other your regex within one same, would:
var testes = [
0, 1, 2, 3, 4, 100, 200, 300, 900, 1000, 2000, '01000', '01', '0100'
];
for (var i = 0, j = testes.length; i < j; i++) {
console.log(`Valor: ${testes[i]} retorna:`, valida(testes[i]));
}
function valida(input)
{
return /^([1-9]\d{0,2}|1000)$/.test(input);
}
The [1-9]
checks whether the value starts from 1 to 9, that is, it can never start with zero
The \d
check if it is number, it is equivalent to [0-9]
, while the {0,2}
checks if the sequence is number, the 0
before the comma indicates that you do not need to have anything after the comma ,2
indicates that it must have a maximum of 2 digits (the [1-9]
would be the other "digit")
So what is before |
must [1-9]\d{0,2}
indicates that "strings" from 1 to 999 are accepted and after |
is the value 1000
, as requested in question, from 1 to 1000
@Diogo ambiguity of use scenarios so it is not possible to determine which is the optimal alternative because JS Regex and PHP PCR have syntax differences, example
[^]
. AP should leave only one language or another.– Augusto Vasques