1

Would someone take a look at my regex please? I'm trying to validate a regex group but it is matching too greedily.

/*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

Edit

Thanks for the help folks. Here is the code with capturing group syntax in ES2018 for those who want to know: (?<iban>^BE\d{14}$)

8
  • 3
    Try var re = /^BE[0-9]{14}$/ Commented Mar 15, 2019 at 14:00
  • why is <iban> in your reg exp?? Commented Mar 15, 2019 at 14:01
  • 1
    @WiktorStribiżew's regex will do what you want - why do you have all this extra stuff in your regex, like <iban>? If this is relevant to the problem you're trying to solve, please explain. Commented Mar 15, 2019 at 14:02
  • 1
    @AndersonPimentel In JS, no matter what to use. Here, copy/paste. Commented Mar 15, 2019 at 14:12
  • 1
    @Pointy JS ECMAScrpt 2018 supports named groups. Commented Mar 15, 2019 at 14:17

1 Answer 1

1
var re = /^BE\d{14}$/; 

Explanation:

  • ^ - marks start of expression
  • BE - literal characters'BE'
  • \d - any digit (same as [0-9])
  • {14} - quantifier - exact 14
  • $ - marks end of expression

All extra stuff was not needed.

You can try it here: https://regex101.com/r/4wF3NG/1

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer would be much more helpful if it included an explanation of what you changed and why you changed it.
thanks for the answers @Anderson Pimentel, and the all you folks. I added the <iban> because it's a a new thing in javascript on ES2018 perhaps, not needed but was giving it a try. Thanks for the explanation @all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.