Help me understand why \w* is necessary

What’s happening:

Why is \w* needed to match my string in this javascript regex code? I see how the code can be correct with it, but why is it incorrect without it?

This Is The Right Answer


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

This Is The Right That Looks Right To Me, But Is Not Correct


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

Can someone help me understand why it is incorrect? I interperet the (?=\d{2,}) to mean that as long as there are two consecutive digits the string will be returned. I don’t understand why we need to specify that letters are coming before it.

browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

Hey welcome to forum :slight_smile:

You want your regex to match passwords that have two consecutive digits somewhere in the string.

If the \w* is omitted then the regex requires that the two consecutive digits immediately follow the non-digit at the start of the string. By putting the \w*, your regex allows for zero or more characters in between the non-digit at the start of the string and the two consecutive digits.

This answer may also be useful to you: Regular Expressions: Positive and Negative Lookahead Questions

2 Likes

Thank you for the answer, and the related posting you referenced to, that makes a lot of sense!

I appreciate it!

1 Like