Regular Expressions - Positive and Negative Lookahead

I am very curious.
This regex:
let pwRegex = /(?=\w{6})(?=\w*\d{2})/
is different than

let pwRegex = /(?=\w{6,})(?=\d{2})/

But why? Both seem to look for 6 characters or more.
Also, why exactly 2 digits? A password that has more than 2 digits still has consecutive digits.
I also thought that its length must be greater than 5 overall not just have characters 5 or more then have exactly 2 digits.
I guess characters means characters only. But then /w gives us alphanumerics…
Is that what characters means in general and if so how do we differentiate between only characters but not including digits?

I think the lessons on lookahead aren’t complete, maybe by design.

let pwRegex = /(?=\w{6})(?=\w*\d{2})/
The above regex works for all tests but I don’t understand why it works for:
8pass99
it’s 6 characters and then a 9. It seems like the second lookahead is not searching from after where the first one got the match?

I think I don’t understand.

hi there,

It would be good to get a link from you for the challenge you are on as it wasn’t posted in your opening topic.

(as well as any links to code that you are referring to in the question if the code is from a solution for eg etc please post the link)

Regex can be complex and confusing but I find this resource extremely helpful:
Regular Expressions - Positive and Negative Lookahead

You are correct. Lookaheads and Lookbehinds are known as zero-length asssertions, so a match is made but do no characters in the string are consumed. So in this case, it is as if both of the lookaheads start from the beginning of the string. Since there are only lookaheads in this regex, they both must match independently to be considered an overall match.

1 Like