[英]Regular Expression - How can I match all numbers less than or equal to Twenty Four?
I'm somewhat new to regular expressions and am writing validation for a quantity field where regular expressions need to be used. 我对正则表达式有些陌生,并且正在为需要使用正则表达式的数量字段编写验证。
How can I match all numbers less than or equal to 24? 如何匹配所有小于或等于24的数字?
I tried 我试过了
var pat = /^[1-9]$|^[1-2]\d$|^3[0-6]$/;
But that only matches 1-24. 但这只匹配1-24。 Is there a simple way to match all possible numbers less than or equal to 24?
是否有一种简单的方法可以匹配所有小于或等于24的数字?
I won't recommend you to use regex just to check if a number is between the range. 我不建议您仅使用正则表达式来检查数字是否在范围内。 To compare the numbers comparison operators should be used.
要比较数字,应使用比较运算符。
if (number >= 0 && number <= 24)
However, if this is not feasible/possible, you can use regex. 但是,如果这不可行/不可能,则可以使用正则表达式。
You can also use 您也可以使用
^(2[0-4]|[01]?[0-9])$
Explanation: 说明:
^
: Start of line anchor ^
:行锚的起点 2[0-4]
: Matches 2
followed by any number between 0 to 4 - Matches 20-24 2[0-4]
:匹配2
后跟0到4之间的任意数字-匹配20-24 |
: OR condition in regex [01]?[0-9]
: [01]?
[01]?[0-9]
: [01]?
: Matches 0 or 1 optionally. [0-9]
: Matches any number exactly once in the range 0 to 9 - Matches 0-19 [0-9]
:与0到9范围内的任何数字完全匹配一次-匹配0-19 input:valid { color: green; } input:invalid { color: red; }
<input pattern="(2[0-4]|[01]?[0-9])" />
You can use following regex 您可以使用以下正则表达式
^(2[0-4])|(^[01]?[0-9])$
^(?:[0-9]|[1][0-9]|2[0-4])$
Try this.See demo. 试试看。看演示。
https://regex101.com/r/iJ7bT6/3 https://regex101.com/r/iJ7bT6/3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.