# Question about Regular Expressions: Positive and Negative Lookahead

Hi everyone.

I’m trying to understand how lookaheads work, so I tested the following code, based on the challenge on topic:

``````let sampleWord1 = "astrona88ut";

let sampleWord2 = "astron88aut";

let testRegex = /(?=\w{5,})(?=\d{2})/;

console.log(testRegex.test(sampleWord1));   // Returns False

console.log(testRegex.test(sampleWord2));    //Returns True
``````

Can anyone explain to me why I got False and True, respectively?

Thanks!

Yes but it isn’t easy =)

The regex `/(?=\w{5,})(?=\d{2})/` is a single expression, not two separate ones. It also is very literal in that you are telling it to find at least 5 characters that begin with two digits.

That’s why this regex `/(?=\w{5,})(?=\D*\d{2})/` returns true for `sampleWord1`. It looks for 5 characters that start with at least one non digit followed by two digits.

I hope that’s somewhat clear.
-J

Hi Jesse. Thank you for your answer.

The regex `/(?=\w{5,})(?=\d{2})/` is a single expression, not two separate ones. It also is very literal in that you are telling it to find at least 5 characters that begin with two digits.

I think I understand what you mean. But if that is the case, why did `console.log(testRegex.test(sampleWord2))` return `True` on my code? The two digits were not at the beginning, but in the middle of the word ( `let sampleWord2 = "astron88aut";).`

Because there is an instance of a 5-character set that starts with 2 digits “88aut”. In `sampleWord1` it was “88ut” which fails the test.

`/(?=\w{5,})/` //Is there a set of at least 5 characters?

`/(?=\d{2})/` //Is there a set of exactly two digits?

`/(?=\w{5,})(?=\d{2})/` //Is there a set of at least 5 characters that starts with exactly two digits?

`/(?=\w{5,})(?=\D*\d{2})/` //Is there a set of at least 5 characters that contains exactly two digits and may or may not start with one or more non-digits?
-J

2 Likes

Got it! Your explanation was superb now. I was losing my mind over this, lol.

Thank you very much!!

1 Like