Lookahead Regular Expression

    let str='bana12';
	let regex1=/^[a-z]/;
	let regex2=/\w{5,}/;
	let regex3=/\d{2}/;
	
	let regexall=/(?=^[a-z]\d)(?=\w{5,})(?=\d{2})/;
	
	let result1=regex1.test(str);
	let result2=regex2.test(str);
	let result3=regex3.test(str);
	let resultall=regexall.test(str);
	
	console.log(result1,result2,result3,resultall);

The results are true, true, ture and false.
Why is the regex3 true when tested alone but false when using Lookahead?

the lookaheads not advance the place in the string that it is looked at, so all of them start looking from the start of string, so you are saying that the string should start with [a-z] and \d at the same time

you can add the ^ anchor at the other two here and see how to make each of them match

1 Like

so my understanding is that :
For regex1/2/3, the string is tested respectively. That’s why result3 is true though β€œ\d{2}” exits only at the end of the string.
For regexall, the string is tested by β€œ^[a-z]” and "\d{2} " simultaneously. When the test finds an alphabet beginning , it still needs to check whether the beginning is consisted of two numbers, instead of checking whether other parts of the string are matched.
In other words, all regulars are tested at the same place!
Thank you very much for your answer! :grinning: