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@  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.84.112