Questions: Regular Expressions Positive and Negative Lookahead

I read related topics, but still unclear. So build a new topic.

Following is the model answer for the task of “Positive and Negative Lookahead”.

let sampleWord = "astronaut";
let pwRegex =  /(?=\w{6})(?=\w*\d{2})/;
let result = pwRegex.test(sampleWord);

I understand the following line

 /(?=\w{6})(?=\w*\d{2})/

…means that
1 this code should match the value of at least 8 characters or numbers because there are “\w{6}” and “\d{2}”.
2 this code should match the value that ends with 2 numbers because this code ends with “\d{2}”.

However, this code returned true when the variable “sampleWord” is “a12bcd”, that has only 6 characters and numbers in total, and ends not with numbers.

I tried to figure out on google and FCC topics, but haven’t cleared yet. If anyone tells me its very much appreciated. Thank you.

nowhere it says that the number needs to be at the end.

this is saying that there must be 0 or more \w characters followed by 2 \d characters, but it doesn’t say anything about the end of the string

2 Likes

Thank you ilenia,
then, the two codes \d{2}\w* and \w*\d{2} mean the same thing?

(?=\w{6})(?=\w*\d{2}) and (?=\w*\d{2})(?=\w{6}) are the same as well?

these two yes

these two mean different things, as you are changing the order of the pattern elements

Instead if you change the order of the lookaheads it doesn’t change anythign as the two lookaheads look from the same position

1 Like

I undeerstand, thank you.

And as I note before I have one more questions,

 /(?=\w{6})(?=\w*\d{2})/

I understand this code needs at least 8 characters (including 2 numbers) in total because it has \w{6} and \d{2}. I mean 6 + 2 = 8.

But why like “a12bcd” returns true?

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