Regular expressions limit number

Asked

Viewed 2,182 times

-4

With regular expressions, such as limiting a minimum and maximum number of a string.

I have a field where I can add 1 to 4 characters. But the numbers should be from 1 to 1000. This way you cannot start with 0.

How to do with regular expression:

^([^10]{1})[0-9]{3}
  • 2

    @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.

1 answer

2

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 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

  • Who negative could point out where I failed in the answer? If there is something wrong I want to know to improve or correct what I wrote. Grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.