Invalid (non-existing) backward or forward references

The Java regular expression engine handles back references to non-existing groups in the same manner as back references to existing groups. Invalid or non-existing back references do not participate in the match. This means that a regular expression with an invalid back reference always fails, although it does not cause any exception.

For example, consider the following regex example:

    (apple|orange|banana)\2 

The \2 back reference will be invalid because there is only one capturing group in this regular expression. Hence, the back reference of \2 always makes it a failed match against any input.

The same happens even when we have a regex pattern as follows:

    \1 

Due to a similar rule, ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.