最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to check a simple number between [0-6] - Stack Overflow

programmeradmin2浏览0评论
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)); returns 3 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
Add a ment  | 

4 Answers 4

Reset to default 6

Your 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]+$/; 
发布评论

评论列表(0)

  1. 暂无评论