Lookahead assertion can work like a type of intersection of regular expressions, but why? (JavaScript)

49 views Asked by At

according to this post in stack overflow, lookahead assertion can work like a type of intersection of regular expressions, but I really have no idea why it works. can someone explain to me?

Look at this code:

console.log("hello world".match(/(?=[a-z])[^aeiou]/ig));

That provides an array of all consonants in this string:

['h', 'l', 'l', 'w', 'r', 'l', 'd']

It seems that the instruction

(?=[a-z])[^aeiou]

works like an intersection between [a-z] and [^aeiou]

No matter how much I try and do tests, I don't understand it (I'm a beginner) and I didn't find anything more interesting than the post above.

Could I, even more, get the intersection between many sets? (regular expressions)

Thanks for help!

1

There are 1 answers

0
Barmar On

A lookahead performs a match test without consuming the portion of the input that was matched. Since it doesn't consume, anything you put immediately after the lookahead will be matched at the same place. So it has to match both the lookahead and the following pattern in order for the regular expression to match, which makes it an AND relationship.