Use Lookaheads in Regular Expressions

Joe Maddalone
InstructorJoe Maddalone

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

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

[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.