Question regarding Regular Expressions: Positive and Negative Lookahead

Tell us what’s happening:
I do not understand why it is passing the “astr1on11aut” string but not passing
"bana12"“abc123”…would be glad if anyone could clr the difference?

Your code so far


let sampleWord = "astronaut";
let pwRegex = /(?!^\d*)(?= *\d\d)(?=\w{5,})/; // Change this line
let result = pwRegex.test(sampleWord);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Positive and Negative Lookahead

Link to the challenge:

hey there, i have looked through your answer and i would like to draw your attention to the fact that yo are regex is not checking for word characters within the sampleword, i added \w* in the second grouping ’ (?= *\d\d)’ and it passed all tests, i think your regex doesnt account for consecutive digits at the end of the sample word, this however results in 8pass99 test not passing, and you can get rid of the first negative lookup and justuse regex instead (^\D) to ensure the number doesn’t start the sample word.

1 Like

thank you for your time and effort.
I have one more question …
can you tell me why the negative lookup doesnt yield results while putting in ^\D
does?
It seems as if it is being overlooked as 8pass99 is being allowed.
thanks in advance

probably because you wrote \d* which is zero or more numbers
if you also give the chance of zero things, then everything is allowed, I think

or the negative lookahead is not supported by your browser - that’s also a chance.

1 Like

This is an interesting question, i also wondered the same and used .test() to check and it seems the negative lookup matches from the second character, i.e sees first character doesnt match and goes to the second character which matches and thus passes the test.
try this test and see what i mean

let sampleWord = "8pass99";
// let pwRegex = /(^\D)(?=\w*\d\d)(?=\w{5,})/; // Change this line
let pwRegex =  /(?!^\d)(?=\w*\d\d)(?=\w{5,})/

let result = sampleWord.match(pwRegex)
console.log(result);

interchange both and you will see how they match on the console.

1 Like

to avoid this issue you can probably put the anchor at the beginning of the regex instead of the lookaround parenthesis: /^(?!...)

2 Likes

this one works perfectly