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

Already subscribed? Sign In

Autoplay

    Use Lookaheads in Regular Expressions

    Joe MaddaloneJoe Maddalone

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

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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...

    00:25 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.

    00:39 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.

    01:00 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.

    01:18 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.

    Discuss

    Discuss