Regular expressions (positive lookahead and negative lookahead)

Regular expressions (positive lookahead and negative lookahead)

Positive lookahead

“Assert that the regex below can be matched, starting at this position”.

Let’s go with this little example:

Regex:
\s+\w+(?=\.)

This would mean, match a space between one and many times followed by a word character between one and many times only if there is a dot following the previous match:

Example:

andy mypass ok orange..see what is going on

The matched text here would be orange (Because there was a dot after “orange”, ah yes, and many spaces before).

Negative lookahead

“Assert that it is impossible to match the regex below starting at this position”.

The regex changes to:
\s+\w+(?!\.)

Do you see the difference?. this should read now:

Match a space between one and many times followed by a word character between one and many times only if the following character is not a dot, so what is matched now using our previous.

Example:

mypass (Because after "mypass" was a space)
ok (Same reason using the word "ok")
orang (Because after "orang" there is an e)
see (Because after "see" there is a space)

…. and so on

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s