Comparing Positive and Negative Lookahead in REGEX

Method 01:
Code:

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

Output:

Passed

Method 02:
Code:

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

Output:

// running tests
Your regex should not match "8pass99"

But why method 02 is not working? What is the difference
between (?!^\d) and (?=^\D) ?

Hello there,

The issue here is that it is within a lookahead. So, the start of line assertion is not doing what you expect - asserting to look from the start of the line. INSTEAD, it is asserting that, once the condition (\d) is true, declare that as the start of the line. Essentially, it has said: 'Move the start of the line to here ___

So, what you want is:

^(?!\d)

I am not sure if that is the technical way to explain it, but is the only way I can describe it.

1 Like