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

Use atomic group to avoid backtracking and fail fast

Recall from Chapter 6, Exploring Zero-Width Assertions, Lookarounds, and Atomic Groups, that an atomic group is a non-capturing group that exits the group and throws away all the alternative positions remembered by any token inside the group, after the first match of the pattern inside the group. Thus, it avoids backtracking to attempt all the alternatives present in the group.

Due to this very characteristic of atomic groups, the use of atomic groups in certain scenarios saves many unnecessary backtracking steps and speeds up the overall regex execution.

So, use this atomic group:

\btra(?>ck|ce|ining|de|in|nsit|ns|uma)\b 

It is better to use the preceding atomic group instead of the following ...

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