Regular Expressions - Positive and Negative Lookahead

I seem to be stuck. Any help would be greatly appreciated.

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.47

Challenge: Regular Expressions - Positive and Negative Lookahead

Link to the challenge:

Lets start off with the (?=\w{5,}) part. You need to have more than 5 chars which means that this will pass if we have exactly 5 characters. It will pass for more as well but we shouldn’t be passing for 5 chars.

When it comes to (?=\d\d), this is probably the way I did it my first time as well, and I’d suggest you try to think here what the whole password needs to look like in order to be parsed correctly instead of just requiring 2 numbers.

Good video to go over regex from Fireship

The code snippet you provided has an error in the pwRegex regular expression. The purpose of this regular expression is to validate whether the sampleWord string meets certain conditions, but the current regular expression is not doing what is intended. Here are the problems:

 (?=\w{5,}): This part of the regular expression is used to check if there are at least 5 alphanumeric characters in the string. However, it doesn't actually check if all the characters in the string are alphanumeric, but only checks if there are at least 5 alphanumeric characters somewhere in the string. This means that a string like "astronaut1" would pass validation, but a string like "astr1" would also pass validation.

 (?=\d\d): This part of the regular expression is used to check if there are at least two digits in the string. However, similar to the first part, it only checks if there are at least two digits somewhere in the string, rather than checking if all characters are digits.

Update. Solved the problem but didn’t really understand this part: (?=\D*\d\d)/

So why do we use \D*? Shouldn’t there be only 2 consecutive digits at the end?

The regular expression you mention, (?=\D*\d\d), is a search pattern used in the context of regular expressions.

why do we feel the need to exclusively state \D*

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.