Unique Marketing, Guaranteed Results.

Regular Expression Lookahead

June 10th, 2009 by Aaron Murphy

Using standard regular expressions is pretty easy for most tasks. However, there is one task that requires lookaheads. I am referring to using negative lookahead to check for strings that do not follow a desired match. The syntax is

(?!someregexp)

where “someregexp” is a regular expression to match. The negative lookahead will reverse the logic for you. So when I needed to find all Master’s degree programs except Master of Science, I used something like

master(?!\sof\sscience)

to match say “master of arts” or “master” but not “master of science”.

The lookahead doesn’t move the position, so you can think of it as saving the spot it was in, checking forward, then returning. If you like regular expressions, you should experiment with lookaheads to get a feel for what they can do. I like to use rublar, a ruby regular expression editor and tester.

  • Facebook
  • Google Bookmarks
  • email
  • NewsVine
  • Slashdot
  • Technorati
  • Yahoo! Buzz
  • BlinkList
  • Print
  • Propeller
Filed under: Programming — Tags: , , , — Aaron Murphy @ 4:11 pm on June 10, 2009

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment


Copyright © 2005-2011 PMA Media Group. All Rights Reserved