admin管理员组文章数量:1389749
var number = '731231';
var myRegex = /[0-6]/;
console.log(myRegex.test(number));
Can anyone explain this ?
IMO the regex written as [0-6] will only check for numbers between 0 and 6 but in the above case the value as large as 731231 is also evaluated to be true
var number = '731231';
var myRegex = /[0-6]/;
console.log(myRegex.test(number));
Can anyone explain this ?
IMO the regex written as [0-6] will only check for numbers between 0 and 6 but in the above case the value as large as 731231 is also evaluated to be true
Share Improve this question asked Jan 29, 2014 at 11:35 aeloraelor 11.1k3 gold badges34 silver badges48 bronze badges 5-
It tests whether a character of your string matches [0-6]
3
surely does. – Moritz Roessler Commented Jan 29, 2014 at 11:38 -
console.log(number.match(myRegex));
returns3
as the first number it matches. – Andy Commented Jan 29, 2014 at 11:38 - 2 As a side note - this isn't a good use for regex. – Emissary Commented Jan 29, 2014 at 11:40
- @Emissary why are you saying so ? – aelor Commented Jan 29, 2014 at 11:57
-
1
Regex is notably slower (reasons already documented all over SO), you may argue that the difference can be negligible but it's just lazy. Regex is for parsing strings character by character, you are dealing with a number (a single entity) - there are specific parison operators and
Math
logic which are far more flexible and robust when handling numbers. – Emissary Commented Jan 29, 2014 at 13:00
4 Answers
Reset to default 6Your regex matches, when there is any such digit present. If you want to match only such digits, use
/^[0-6]+$/
This matches a string with any number of digits from 0-6. If you want a single digit, omit the +
:
/^[0-6]$/
You're checking if there is somewhere a number between 0 and 6, which is the case.
var number = '731231';
var myRegex = /^[0-6]+$/;
console.log(myRegex.test(number));
UPDATE
Though, if you want the string to match a number satisfying the rule 0 >= N <= 6
This would be what you want
var myRegex = /^[0-6]$/;
Yiu should use
var myRegex = /^[0-6]$/;
you're looking for a string that starts ^ then contains one 0..6 digit and immediately ends $
Your implementation /[0-6]/
is looking for a 0..6 digit anywhere within the string, and that's why 731231 meets this criterium.
Your regex is checking to see if one of the following appears in the string:
0, 1, 2, 3, 4, 5 or 6
and that is true because there is 1, 2 and 3 in there.
If you want to check that the whole string is a number then you could use:
var myRegex = /^[0-9]+$/;
本文标签: javascriptRegex to check a simple number between 06Stack Overflow
版权声明:本文标题:javascript - Regex to check a simple number between [0-6] - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744630411a2616502.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论