Positive and Negative Lookahead question about * character

the above code looks for between 3 and 6 characters and at least one number

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

I don’t understand this part:


we have all non-numbers followed by * and all numbers
why the * in between?

1 Like
  • (?=\D*\d)

The character class \D is equivalent to [^0-9] both meaning “no Arabic numerals”.

And * means 0 or more. So that means that you can have any number of symbols (not 0-9) and at some point needs a number.

I am not sure look-aheads make sense outside match, because they basically mean “match something” if it is followed “by something else”.

So, match “cat” if there is a “dog”. But if you want to test, just add both.

rex = /cat(?=\s.*\sdog)/
str = "cat oh and the dog"

If you remove the look ahead it will match all the sentence.

But that regex without the look ahead isn’t very different in the case of testing.

why couldn’t it be without the * character?

let checkPass = /(?=\w{3,6})(?=\D\d)/;

The two lookahread start looking at the same position. Your code means that of the 3-to-6 characters matched in the first lookahead, the first one must be a non-number (\D) and the second one a number (\d)

Yes, just adding up to that:

a = /(?=a)(?=b)/

that will always be false, something can’t be both a and b at the same time

My point is that both will be looking at the first character, if you run

a = /(?=a)(?=.b)/

it will be true

The first look up does not indicate “only a” but “there is a” imho.