[英]Regular expression to match specific number of digits
I am trying to write a regular expression which returns a three digit integer only. 我正在尝试编写一个仅返回三位数整数的正则表达式。 Not less than three or more than three.
不少于三个或大于三个。 However my regex below is also true for four digit numbers.
但是我下面的正则表达式对于四位数也是正确的。 Am i missing something?
我想念什么吗?
var threeDigits = /\d{3}$/
console.log(threeDigits.test("12"))// false
console.log(threeDigits.test("123"))// true
console.log(threeDigits.test("1234"))// true yet this is four digits???
You have the ending anchor $
, but not the starting anchor ^
: 您有结尾锚
$
,但没有起始锚^
:
var threeDigits = /^\d{3}$/
Without the anchor, the match can start anywhere in the string, eg 没有锚,匹配可以在字符串中的任意位置开始,例如
"1234".match(/\d{3}$/g) // ["234"]
使用一个^ [0-9] {3} $或^ \\ d {3} $。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.