Use lazy quantifiers strategically instead of greedy quantifiers that cause excessive backtracking

Suppose we need to match an input that contains three complete words, start, middle, and end, separated by non-whitespace characters.

Consider using the following pattern with a lazy quantifier:

\bstart\b\S+?\bmiddle\b\S+?\bend\b 

Instead of using the following pattern, our match will be faster if we use the preceding pattern:

\bstart\b\S+\bmiddle\b\S+\bend\b 

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.