Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Negative lookahead assertions

From: Using Regular Expressions

Video: Negative lookahead assertions

So far, we've been talking about positive lookahead assertions, but they have an opposite, which are negative lookahead assertions, and the metacharacters we use for negative lookahead assertions are the question mark, followed by the exclamation point. The way we use them is the same way that we use the positive ones. Inside a grouped expression, the very first character inside the parentheses should be a question mark, then an exclamation point, and then our regular expression. The question mark indicates that this grouped expression has a different meaning than normal, and the exclamation point means that, that meaning is negative, or not equal. The exclamation point makes sense, because in many programming languages, exclamation point is used to mean not.

Negative lookahead assertions

So far, we've been talking about positive lookahead assertions, but they have an opposite, which are negative lookahead assertions, and the metacharacters we use for negative lookahead assertions are the question mark, followed by the exclamation point. The way we use them is the same way that we use the positive ones. Inside a grouped expression, the very first character inside the parentheses should be a question mark, then an exclamation point, and then our regular expression. The question mark indicates that this grouped expression has a different meaning than normal, and the exclamation point means that, that meaning is negative, or not equal. The exclamation point makes sense, because in many programming languages, exclamation point is used to mean not.

So if we had an exclamation point, followed by an equal sign, it would be used to mean not equal. Well here, we are just using the exclamation point by itself to mean negative; not this regular expression. Be careful that there is no space after the exclamation point. You just start your regular expression right away. If you put in a space, it becomes part of the expression, and gives it meaning. To see this in context, it works the same way as our positive ones did, except it returns the opposite set of results. So for example, if we had negative lookahead for seashore, followed by sea, that would match sea inside seaside, but not in seashore.

It still matches the same thing; S, E, A, but it's looking ahead, and looking for the opposite case; the case when seashore is not what it finds. If you step through it the way that the regular expression engine does, it first checks to see, do I find seashore? And if it does find it, it says, nope, it's a failure then, it's not a match, and we move on. If it doesn't find seashore, then it rewinds and checks for S, E, A, and makes the match. And of course, we can write that in the reverse by putting sea, and then have a negative lookahead assertion for shore after it.

So match sea, then look ahead, and see if the next part is shore. Now, it's easy to overlook the power that these give you, because you may think, oh, well they're just the opposite of positive lookahead assertions. But, here's the thing. regular expressions so far have not had a way for us to talk about when not to match something. We had negative character sets, which allowed us to rule out characters, but there's no other way to talk about when to not match an entire pattern. Negative lookaheads give us a way to describe expressions that should be rejected.

That's an important and powerful tool. So, for example, let's say we wanted to find the word online. We wanted to find it only in cases when it wasn't followed by training. So we could have an expression that was online, and then a negative lookahead for space training. That would not match online training, but it would match online courses. Even more powerful, we can use wildcards to say that there might be words in between. So we want to find online anytime that it's not followed by training, even though there might be words like video in between. So we'd find online videos, and online courses, but not online video training.

Let's try some more examples. Let's start with this sentence. I am going to paste in, The black dog followed the black car into the black night. So you see we've got the word black three times, and we can write a regular expression that will match the word black using the word boundaries on either side to make sure we get just that word, and it matched it three times. Well, we can use our negative lookahead assertion like that, with a regex in the middle, and say we want to find it anytime it is not black followed by dog. So now we found the other two, but we've ruled out the one.

Of course, that's the opposite of if we had the equal sign there, which would find black when it is followed by dog, but not any other time. Let's try the phone number example that we had before. We had three different phone numbers, and we wrote ourselves a regular expression that would check it three different times. It checks to make sure that the digits are zero to five, it checks to make sure that it has four, three, two, one in it, and it makes sure that it matches the format of the phone number. We also need to turn on multi-line anchors here, because we put the phone numbers on separate lines, and we're using anchors around this expression.

So what if we wanted to change this one to a not? Now, it finds things that are zero to five, but that do not have the sequence four, three, two, one in it, and that still match the pattern. We've used a combination of a positive lookahead, and a negative lookahead. The negative lookahead's purpose is really to rule out a case. To say, I want to find everything, but I know something about a special case that I want to rule out here, and make sure that we don't include in the match. That's simple, but it's actually very powerful. Let's try our Self-Reliance example, with the words followed by commas.

I am just going to copy that Self- Reliance text again. Let's paste this in here, and the regex that we had written before was like this, and this finds all words; look ahead positively for words that have a comma after them. If we wanted to find words that do not have a comma, well then we just change it like this. Now, it finds all those other words; words that do not have a comma after them. We could go ahead and put it inside a character set, and add period in there as well. Now it's words that are not followed by a comma or a period. So I think you get the idea. I want to show you one last way that this can be really useful.

I am going to go back to my black dog text here, and let's put in our text again, black, that we are going to match. What if I wanted to find the last occurrence of the word black? It's not about the specific text that immediately follows it; I want the last one. That can be a very useful and powerful tool. Well, if you think about it logically, the last occurrence of the word black is anytime that the word black isn't followed by itself. So all we have to do is write a negative lookahead expression, and say that any number of characters -- I don't know how many -- followed by the word black; we'll put those word boundaries again.

Now, it says, okay, I found black that doesn't have black coming after it. It's the last occurrence, in that line, of black. Even better, you can put our grouped expression here, and we'll capture that group, and then we can just use backslash one to refer to that captured group. Remember how we did that when we learned about backreferences? So now it finds the word black, and any time that it's not followed by itself, it's the last occurrence. This is a very useful pattern, and one that's definitely worth remembering. Hopefully now you appreciate some of the power that lookaround assertions give you.

But we've only looked at one half of lookaround assertions: the lookahead assertions. That's looking forward. We also have the ability to look backwards by using lookbehind assertions, and that's what we'll look at in the next movie.

Show transcript

This video is part of

Image for Using Regular Expressions
Using Regular Expressions

59 video lessons · 11665 viewers

Kevin Skoglund
Author

 
Expand all | Collapse all
  1. 2m 18s
    1. Welcome
      56s
    2. Using the exercise files
      1m 22s
  2. 19m 55s
    1. What are regular expressions?
      3m 20s
    2. The history of regular expressions
      6m 40s
    3. Regular expression engines
      2m 44s
    4. Installing an engine
      4m 5s
    5. Notation conventions and modes
      3m 6s
  3. 21m 23s
    1. Literal characters
      6m 39s
    2. Metacharacters
      2m 1s
    3. The wildcard metacharacter
      4m 31s
    4. Escaping metacharacters
      4m 53s
    5. Other special characters
      3m 19s
  4. 31m 26s
    1. Defining a character set
      5m 49s
    2. Character ranges
      4m 49s
    3. Negative character sets
      4m 53s
    4. Metacharacters inside character sets
      5m 12s
    5. Shorthand character sets
      6m 30s
    6. POSIX bracket expressions
      4m 13s
  5. 36m 38s
    1. Repetition metacharacters
      7m 17s
    2. Quantified repetition
      6m 59s
    3. Greedy expressions
      6m 27s
    4. Lazy expressions
      6m 46s
    5. Using repetition efficiently
      9m 9s
  6. 20m 24s
    1. Grouping metacharacters
      4m 14s
    2. Alternation metacharacter
      4m 54s
    3. Writing logical and efficient alternations
      7m 33s
    4. Repeating and nesting alternations
      3m 43s
  7. 19m 19s
    1. Start and end anchors
      7m 21s
    2. Line breaks and Multiline mode
      4m 41s
    3. Word boundaries
      7m 17s
  8. 23m 33s
    1. Backreferences
      8m 57s
    2. Backreferences to optional expressions
      3m 51s
    3. Finding and replacing using backreferences
      7m 16s
    4. Non-capturing group expressions
      3m 29s
  9. 32m 31s
    1. Positive lookahead assertions
      6m 39s
    2. Double-testing with lookahead assertions
      7m 16s
    3. Negative lookahead assertions
      6m 10s
    4. Lookbehind assertions
      6m 26s
    5. The power of positions
      6m 0s
  10. 13m 13s
    1. About Unicode
      4m 19s
    2. Unicode in regular expressions
      4m 41s
    3. Unicode wildcards and properties
      4m 13s
  11. 1h 55m
    1. How to use this chapter
      5m 38s
    2. Matching names
      6m 33s
    3. Matching postal codes
      8m 54s
    4. Matching email addresses
      5m 0s
    5. Matching URLs
      8m 1s
    6. Matching decimal numbers and currency
      6m 45s
    7. Matching IP addresses
      7m 10s
    8. Matching dates
      7m 49s
    9. Matching times
      8m 59s
    10. Matching HTML tags
      8m 34s
    11. Matching passwords
      6m 49s
    12. Matching credit card numbers
      9m 36s
    13. Finding words near other words
      6m 38s
    14. Formatting with Search and Replace, pt. 1
      7m 22s
    15. Formatting with Search and Replace, pt. 2
      4m 15s
    16. Formatting with Search and Replace, pt. 3
      7m 10s
  12. 47s
    1. Goodbye
      47s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Using Regular Expressions.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.