The \D* in Positive and Negative Lookahead Challenge

**Why there is \D* in this challenge example? **
Sorry about repeative topic, I know there are some topic about this. However, I still find it hard to understand in the checkPass lookahead syntax, why we have to lookahead for any non-number characters \D* before a number character?

let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password);

Why can’t we just code it without the \D* part like this? Is this still mean that we lookahead a string has 3 to 6 characters and ALSO have at least 1 number?

let password = "abc123";
let checkPass = /(?=\w{3,6})(?=\d)/;
checkPass.test(password);

Also, when I type like this:

let password = "abcdefghijk123";
let checkPass = /\w{5,}\d\d/;
console.log(checkPass.test(password));

It returns true (because the first match is abcdefghijk12 idk)

But when I type like this:

let password = "abcdefghijk123";
let checkPass = /(?=\w{5,})\d\d/;
console.log(checkPass.test(password));

it returns false (null)
Can someone please explain why these are different? :frowning:


User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.168 Safari/537.36

Challenge: Positive and Negative Lookahead

Link to the challenge:

the key here is realizing lookaheads/lookbehinds are non-consuming, which is to say unlike a plain old regex, characters matched with lookahead/lookbehinds still exist for the rest of your regex to match with.

Example:
const reg=/\d+[a-z]/;
when this regex matches 1234w, it first sees “1”, “consumes” that character, and move on to “2”. The regex will never ever go back to “1” again. This process repeats until the match fails or succeeds in its entirety.

However:
const reg=/(?=\d+)[a-z]/;
will never be able to find any matches, let’s try with a test string of 123w again.

The regex matches 123, yet does not consume the characters, and on [a-z] it is still on the first character of the string, “1”, which is not a match.

So with your conundrum of /\w{5,}\d\d/ vs /(?=\w{5,})\d\d/ on the test string of
“abcdefghijk123” would be:
the first one consumes the alphabets until the very last two characters of “2” and “3”, which is matched by the two \d at the end. (side note this would be a full match of the string because \w means [a-zA-Z0-9_], the numbers are included).

the second one, the lookahead matches the alphabets, however \d\d at the end still starts matching at the first character “a”, which is not a match.

EDIT: try and play with regex on one of several regex websites such as regex101.com to see how your regex matches certain strings.

1 Like

Thank you for your answer.

1 Like

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