How can I write a regex that limits user input to 3 digits in the range of 0-128?
I've been trying \d{1,3}
but this allows for a match more than the 0-128 range.
Thanks
How can I write a regex that limits user input to 3 digits in the range of 0-128?
I've been trying \d{1,3}
but this allows for a match more than the 0-128 range.
Thanks
Share Improve this question edited Mar 2, 2015 at 19:16 willeM_ Van Onsem 479k33 gold badges476 silver badges614 bronze badges asked Mar 2, 2015 at 18:51 JakeJake 26.1k31 gold badges114 silver badges178 bronze badges 4- Why should this be a RegEx? – thefourtheye Commented Mar 2, 2015 at 18:54
- cuz it's easy to check than me doing if else loops later on. – Jake Commented Mar 2, 2015 at 19:02
-
1
if (parseInt(value, 10) >= 0 && parseInt(value, 10) <= 128)
? – thefourtheye Commented Mar 2, 2015 at 19:03 - 1 agreed.. but what I am doing will go with a regex, that I already have in place. The question here is just a piece of that puzzle. :) appreciate the answer though. – Jake Commented Mar 2, 2015 at 19:12
4 Answers
Reset to default 5You can use this regex:
/\b([0-9]{1,2}|1[01][0-9]|12[0-8])\b/
Use this utility
Excluding 128
You can do this using the following regex:
^0?\d{1,2}|1([0-1]\d|2[0-7])$
You more or less break it down hierarchically.
The first:
0?\d{1,2}
captures all values up to (and including) 99
, optionally with a leading zero (so 064
) is accepted.
Next you capture 1[0-1]\d
. These are the values 100
to 119
. This is because there is no constraint on the last digit.
And finally you have 12[0-7]
, the two first digits are fixed, and you can use 120
up to 127
.
Including 128
In case 128
, is allowed as well, use:
^0?\d{1,2}|1([0-1]\d|2[0-8])$
Leading zeros not allowed
The you can use:
^\d|[1-9]\d|1([0-1]\d|2[0-8])$
Word boundaries
Here I've added the ^
and $
so that the string begins and ends with the number. Otherwise, you can use - as @anubhava suggests - word boundaries \b
. Although one probably better uses:
\b(0?\d{1,2}|1([0-1]\d|2[0-7]))\b
\b(0?\d{1,2}|1([0-1]\d|2[0-8]))\b
\b(\d|[1-9]\d|1([0-1]\d|2[0-8]))\b
Regex is the wrong tool for the job.
<input type="number" min="0" max="128" />
Done.
0 - 128 would be: ^(?:\d|[1-9]\d|1[0-1]\d|12[0-8])$
^
(?:
\d
| [1-9] \d
| 1 [0-1] \d
| 12 [0-8]
)
$
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745299160a4621329.html
评论列表(0条)