Category: regex

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