Use Lookaheads in Regular Expressions

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today