Positive Lookahead Inconsitency

From what I understand from positive lookahead, these check if the conditions are met anywhere in a defined text.

I’ve built 4 different cases. The first one (result ) with my idea of a code (/(?=\w{5})(?=\d{2})/) that should test true from what I understand (but the result is false).

The second one (result1) is the first part ( /(?=\w{5})/) of my original code , which tests true.

The third one (result2) is the second part (/(?=\d{2})/ )of my original code , which tests true.

After this, my question is: how is it possible that the conditions test true when tested independently, and then test false when tested together?

The 4th case (result3) is the complete solution (/(?=\w{5})(?=.\d{2})/) I’ve found to test true. But I consider that adding this () should not be necessary, because this condition is met somewhere ahead in the text. I think it shouldn’t be necessary to specify that characters before the digits are allowed, considering that the Lookahead tests if the conditions are met anywhere in the text, so clarifying this should be redundant the way I see it.

Could someone please explain this to me?

Your code so far


let sampleWord = "bana123";
let pwRegex = /(?=\w{5})(?=\d{2})/;
let result = pwRegex.test(sampleWord);
let pwRegex1 = /(?=\w{5})/;
let result1 = pwRegex1.test(sampleWord);
let pwRegex2 = /(?=\d{2})/;
let result2 = pwRegex2.test(sampleWord);
let pwRegex3 = /(?=\w{5})(?=.*\d{2})/;
let result3 = pwRegex3.test(sampleWord);
console.log(result)
console.log(result1)
console.log(result2)
console.log(result3)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Positive and Negative Lookahead

Link to the challenge:

the two lookaheads start looking at same position. For the pattern you are asking about to be true, you need to have two consecutive numbers followed by other three characters

Thank you very much for your answer, I think I understand now why it wasn’t working. Just to make sure I’m getting it right, does that mean that both Lookaheads are not independent from each other? When put together, they need to be true starting at the same character?

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