O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required