3

I would like to know what the definition for an assertion is in the context of regular expressions. If anyone should know, please enlighten me with a brief definition of what it actually is. I would also appreciate one or two examples of such.

1 Answer 1

5

What is a Regular Expression Assertion?

An Assertion is a Regular Expression that either succeeds (if a match is found) or fails (if a match is not found).

They consist of Anchors and Lookarounds.


Anchors

An Anchor is a zero-width Assertion. They do not cause the engine to advance through the string or consume characters, and can be one of the following:

  • ^ - The match must start at the beginning of the string or line.

  • $ - The match must occur at the end of the string or before \n at the end of the line or string.

  • \A - The match must occur at the start of the string.

  • \Z - The match must occur at the end of the string or before \n at the end of the string.

  • \z - The match must occur at the end of the string.

  • \G - The match must occur at the point where the previous match ended.

  • \b - The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.

  • \B - The match must not occur on a \b boundary.

Source Regular Expression Language - Quick Reference


Lookarounds

Lookahead and lookbehind, collectively called "lookaround", are zero-length assertions just like the start and end of line, and start and end of word anchors.

The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.

Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.

Source Lookahead and Lookbehind Zero-Length Assertions

enter image description here

Source Mastering Lookahead and Lookbehind


Further reading

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .