1

I need a regex for an integer starting from 25 with no limit I tried:

^([2-9]\d[0-9]\d{2,})$

but I need it to start from 25 not 20 and I'm not even sure if this works correctly.

4

5 に答える 5

1

Your regex

^([2-9]\d[0-9]\d{2,})$

Will match any number starting with 2-9 and having 5 digits or more (\d, [0-9] contribute one digit each, \d{2,} is for another two or more digits). You want something like this:

^0*(1\d\d|2[0-4]\d|2[5-9]|[3-9]\d)\d*$

As you can see this is rather ugly. If you are using some kind of programming languages, you should rather assert that it is a number (^\d*$) and check the range without regex.

But how does my regex work?

First we consume leading 0s because they don't change the value of the number. And then we have an alternation depending on the first digit(s) of the number. If it's a 1 we know we need at least two more digits for it to be greater than 25. If it's a 2 and the second digit is between 0 and 4 we also need another digit. If it's 25 or starts with 3 to 9, two digits suffice. And after the alternation, we just allow arbitrarily many more digits.

Working demo.

于 2012-11-29T16:25:50.950 に答える
0

Test it here

^(2[5-9]([0-9])*|[3-9][0-9]+|[1-2][0-9]{2,})$
于 2012-11-29T16:23:29.913 に答える
0

You can also use regex to check the complement of that: (Eliminate anything that doesn't qualify: i.e match any thing that is less than 25)

  • Not anything that starts with - (negative)
  • Not anything that:
    • Starts with [0-2], and
    • Is followed by [0-4], and
    • Is not followed by another digit (If it is followed by another digit, then you have > 200)
  • Not anything that includes a non-numeric character
于 2012-11-29T16:27:44.790 に答える
0

Here is a regex that is slightly more concise than some of the others:

^(?!(1\d|2[0-4])$)[1-9]\d+$

You can test it here: http://www.rubular.com/r/PGdbtGYsWD

The approach is to just match [1-9]\d+, which will be a two or more digit number, and use a negative lookahead at the beginning to prevent matches for any numbers between 10 and 24.

If leading zeros should be allowed, just add 0* directly after the ^.

于 2012-11-29T16:35:25.180 に答える
0

Use regex pattern

^(2[5-9]|[3-9]\d|(?!0)\d{3,})$

or (if you want to allow leading zeros)

^0*(2[5-9]|[3-9]\d|(?!0)\d{3,})$
于 2012-11-29T16:48:10.603 に答える