[英]Regular expression to match specific number of digits
我正在嘗試編寫一個僅返回三位數整數的正則表達式。 不少於三個或大於三個。 但是我下面的正則表達式對於四位數也是正確的。 我想念什么嗎?
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???
您有結尾錨$
,但沒有起始錨^
:
var threeDigits = /^\d{3}$/
沒有錨,匹配可以在字符串中的任意位置開始,例如
"1234".match(/\d{3}$/g) // ["234"]
使用一個^ [0-9] {3} $或^ \\ d {3} $。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.