Regex Lookahead and Lookbehind

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
(? 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.



Comments

Leave a Reply

Webmentions

If you've written a response on your own site, you can enter that post's URL to reply with a Webmention.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.