Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Lookaheads in Regular Expressions


    Lookaheads allow us to match a pattern followed by another pattern without including the second pattern in our match.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    If we wanted to match a pattern that's followed by another pattern but we don't want to include that second pattern in our match, we can use something called a lookahead. I'm going to have just our standard foo, foobar, foobas, and fooboo. Then, in our regx, we are going to set up...

    Let's go ahead and first capture foo. We know how to do that. We've captured all the foos. We also know that we can use a capturing group to capture foobar or fooboo. Now, we're capturing both foobar and fooboo.

    Let's say that we want that result, but we only want to capture foo where it's followed by bar or boo. What we can do is use a lookahead. Right here in our capture group, we do ?=. Save that. You can see that we've actually captured foo where it was followed by bar, and we've captured foo where it was followed by boo.

    We can also do a negative lookahead. Where this is a positive lookahead, meaning we are expecting it to follow the preceding pattern, we can do a negative lookahead, with a ? and !, which means we want to capture foo where it's not followed by bar or boo.

    Save that, and we can see we've captured foo here, where it's not followed by bar or boo, and foo here, where it's followed by bas, which clearly is not bar or boo.