【问题标题】:Regular expression to match specific number of digits匹配特定位数的正则表达式
【发布时间】:2017-05-18 01:09:36
【问题描述】:

我正在尝试编写一个仅返回三位整数的正则表达式。不少于三个或三个以上。然而,我下面的正则表达式也适用于四位数。我错过了什么吗?

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???

【问题讨论】:

  • 你应该使用^\d{3}$,其中^是字符串的开始。

标签: javascript regex


【解决方案1】:

你有结束锚$,但没有开始锚^

var threeDigits = /^\d{3}$/

没有锚,匹配可以在字符串中的任何位置开始,例如

"1234".match(/\d{3}$/g)  // ["234"]

【讨论】:

    【解决方案2】:

    使用 ^[0-9]{3}$ 或 ^\d{3}$ 之一。

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2017-07-02
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      相关资源
      最近更新 更多