【问题标题】:Wrong return when validating regex with JavaScript使用 JavaScript 验证正则表达式时返回错误
【发布时间】:2019-03-15 13:58:31
【问题描述】:

有人可以看看我的正则表达式吗?我正在尝试验证 regex 组,但它的匹配过于贪婪。

/*Should match only 16 characters in total & must begin with BE and follow by 14 digits */ 
 
var re = /(?<iban>[/BE\B/(?={0-9})])/gm
     
let correctIban  = 'BE71096123456769'              // => should match
let badIbanOne   = 'BE13466123456767590kd'         // => should NOT match
let badIbanTwo   = 'BE13466123456767590679080176'  // => should NOT match
let badIbanThree = 'AZ71096123456769'              // => should NOT match

console.log(re.test(correctIban));   // => true
console.log(re.test(badIbanOne));    // => false
console.log(re.test(badIbanTwo));    // => false
console.log(re.test(badIbanThree));  // => false

编辑

感谢各位的帮助。以下是ES2018 中捕获组语法的代码,供那些想知道的人使用:(?&lt;iban&gt;^BE\d{14}$)

【问题讨论】:

  • 试试var re = /^BE[0-9]{14}$/
  • 为什么 在你的 reg exp 中??
  • @WiktorStribiżew 的正则表达式会做你想做的事——为什么你的正则表达式中有所有这些额外的东西,比如&lt;iban&gt;?如果这与您要解决的问题有关,请说明。
  • @AndersonPimentel 在 JS 中,不管用什么。在这里,复制/粘贴。
  • @Pointy JS ECMAScrpt 2018 supports named groups.

标签: javascript regex regex-group


【解决方案1】:
var re = /^BE\d{14}$/; 

解释:

  • ^ - 表示表达式的开始
  • BE - 文字字符'BE'
  • \d - 任何数字(与 [0-9] 相同)
  • {14} - 量词 - 精确 14
  • $ - 表示表达式结束

不需要所有额外的东西。

你可以在这里试试:https://regex101.com/r/4wF3NG/1

【讨论】:

  • 如果您的答案包含对您更改的内容以及更改原因的解释,将会更有帮助。
  • 感谢@Anderson Pimentel 以及你们所有人的回答。我添加了&lt;iban&gt;,因为它可能是ES2018 上的javascript 中的一个新事物,不需要但正在尝试。感谢@all 的解释。
猜你喜欢
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2017-10-27
相关资源
最近更新 更多