1

I am using Regex to match passwords that are greater than 5 characters long and have two consecutive digits in JavaScript.

I tried it two different methods using lookahead, the first method returns false, whereas the second one returns true.

Here is the code:

let sampleWord = "abc123";
let pwRegex = /(?=\w{5,})(?=\d{2,})/; //returns false
let result = pwRegex.test(sampleWord);
console.log(result);

let sampleWord = "abc123";
let pwRegex = /(?=\w{5,})(?=\D*\d{2,})/; //returns true
let result = pwRegex.test(sampleWord);
console.log(result);

The only difference is that the second one also has \D*. As far as I know, it checks for non-numeric values occurring 0 or more times. But why is it required in this case?

P.S. This is a part of a challenge at FreeCodeCamp.org for learning Regular Expressions

VLAZ
  • 18,437
  • 8
  • 35
  • 54
Eagle
  • 266
  • 3
  • 12
  • Consecutive lookaheads are executed at the same location in the string. – Wiktor Stribiżew Mar 21 '19 at 09:06
  • @WiktorStribiżew Okay, but why do we need to check using `\D*` here? Won't just checking for at least two occurances of numeric characters using `\d{2,}` be enough? – Eagle Mar 21 '19 at 09:09
  • `\D*` is not checking anything, it matches 0 or more chars other than digits *to get* to the digits that you want to match with`\d{2,}`. Note that the second one matches also due to the fact that `\w` also match digits as `\d` does, or neither would have worked. – Wiktor Stribiżew Mar 21 '19 at 09:10
  • @WiktorStribiżew Ohkay. That makes sense. Thanks a lot! – Eagle Mar 21 '19 at 09:12
  • I found [an answer](https://stackoverflow.com/a/33355260/3832970) of mine where I explained how lookaheads work. The last sentences actually explain that `\D*` (`[^\d]*`) thing. [Here](https://stackoverflow.com/questions/51876308/strange-js-regex-lookahed), a pattern is discussed that follows the same logic as your regex does. – Wiktor Stribiżew Mar 21 '19 at 12:04
  • @WiktorStribiżew Thanks a lot! It helped. And maybe you could mark this question as a duplicate of that question instead of the one you have marked at present? – Eagle Mar 21 '19 at 12:10
  • 1
    I have changed the duplicate reason. – Wiktor Stribiżew Mar 21 '19 at 12:11

0 Answers0