代码之家  ›  专栏  ›  技术社区  ›  intercoder

用javascript验证regex时返回错误

  •  0
  • intercoder  · 技术社区  · 5 年前

    有人能看看我的正则表达式吗?我正试图验证 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 对于那些想知道的人: (?<iban>^BE\d{14}$)

    0 回复  |  直到 5 年前
        1
  •  1
  •   Anderson Pimentel    5 年前
    var re = /^BE\d{14}$/; 
    

    说明:

    • ^ -标记表达式的开头
    • BE -文字字符“BE”
    • \d -任何数字(与[0-9]相同)
    • {14} -量词-精确14
    • $ -标记表达式结尾

    不需要所有额外的东西。

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