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@  

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.