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

Make use of possessive quantifiers to avoid backtracking

Recall that we discussed in an earlier chapter how a possessive quantifier is used for fail-fast paradigm. Wherever possible, make good use of possessive quantifiers to tell the regex engine to avoid backtracking.

Suppose we need to write a regex to match the text between two markers, @START@ and @END@. It is given that the semicolon is now allowed between two markers.

We can write this regex with the + or greedy quantifier, as follows:

@START@[^;]+@END@ 

However, it is better to use the ++ or possessive quantifier in the regex, as follows:

@START@[^;]++@END@ 

This regex will be faster to execute for failed matches, such as the following string:

@START@ abc 123 foo @XYZ@  

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