Regex Lookahead and Lookbehind

May 2, 2016
Category: TIL
Tags: Regex

Today I learned:

Regex Lookahead and Lookbehind

(?=foo) Lookahead Asserts that what immediately follows the current position in the string is foo
(?<=foo) Lookbehind Asserts that what immediately precedes the current position in the string is foo
(?!foo) Negative Lookahead Asserts that what immediately follows the current position in the string is not foo
(?<!foo) Negative Lookbehind Asserts that what immediately precedes the current position in the string is not foo

Example

Expression: Hell(?=o) - Lookahead

  • Hellish fails
  • Hello passes
  • MelloHello passes

Use

The basic example above isn’t very helpful. But it can be very useful for password rule validation or advanced find/replaces.

Find this post useful?

Buy me a coffeeBuy me a coffee