Question about Regex

Question about Regex
0

#1

I’m confused about how exactly how lookaheads work, for instance in my code below the second test fails despite the fact the ‘sampleWord’ contains something in the character class \d it requires the \D* to pass.

let sampleWord = "astronaut22";
let pwRegex = /(?=\w{5,})(?=\D*\d)/;
let result = pwRegex.test(sampleWord);

console.log(result); // returns true

let sampleWord = "astronaut22";
let pwRegex = /(?=\w{5,})(?=\d)/; 
let result = pwRegex.test(sampleWord);

console.log(result); // returns false

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead


#2

I’m no regex wiz but I’ll give this a shot to the best of my understanding.

/(?=\w{5,})(?=\d)/
Your second lookahead is trying to match a place in your string where a pointer could be placed such that the pointer is immediately followed by 5 or more word characters \w and immediately followed by one digit character \d. Using variations of your password see where your regex will fail.

astronaut false (obviously)
22astronaut true
a22stronaut true
as22tronaut true
ast22ronaut true
astr22onaut true
astro22naut true
astron22aut true (last variation where both are possible)
astrona22ut false
astronau22t false
astronaut22 false

/(?=\w{5,})(?=\D*\d)/
Your first regex is still trying to match a place in your string where a pointer could be placed such that the pointer is immediately followed by 5 or more word characters but allows for the pointer to be followed by zero or more non-digit characters \D* and then a digit character.

This is more flexible about where that digit is in relation to the pointer - it does not have to follow immediately, it just has to be there.

astronaut false (obviously again)
22astronaut true
a22stronaut true
as22tronaut true
ast22ronaut true
astr22onaut true
astro22naut true
astron22aut true
astrona22ut true
astronau22t true
astronaut22 true

Now to pass the challenge your regex would need to test that there are at least two consecutive digits. Your regex as written is only testing for one.

Hope this helps some.


I need a RegEx Guru!