Using Regex Look Arounds

.net supports four types of "Look Around". These can be used to make sure that patterns do or do not appear before or after whatever it is you're matching on. Consider the following text:

"my car will be off the road for 2 days. it's reg num is ab123abc"

If I wanted to pluck out the registtration number, I'd probably start with an expression like

"(?<regnum>[a-z]{2}.?[0-9]{1,3}.?[a-z]{3})"

The problem is, although that expression does indeed return ab123abc as a match, it also returns or 2 day. Using a negative lookbehind and a negative lookahead I can stop the RegEx engine from matching parts of words.

The following expression includes the negative look behind (?<![a-z]) and the negative look ahead (?![a-z]))

"(?<regnum>(?<![a-z])[a-z]{2}.?[0-9]{1,3}.?[a-z]{3}(?![a-z]))"

This only matches on the regnum.

The available "Look Around" expressions are:

?= Positive Look Ahead
?<! Negative Look Behind
?<= Positive Look Behind
?! Negative Look Ahead
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

mark said:

can i use negative lookahead to make sure a string does not contain the substrings mark john paul?

Example regex

(?! mark | john | paul )

18/Feb/2007 01:05 AM

Rick Caldwell said:

Mark, you can definitely use negative lookaheads to disregard Regex matches. I have an example at

<a href="http://www.quisonart.com/techblog/index.php/2007/05/26/using-regular-expression-lookarounds-with-net-to-handle-find-and-replace/">Using Regular Expression Lookarounds</a>. Hope this helps

26/Jun/2007 00:30 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.