Use a compiled form of regular expressions

Compile your string regex pattern using the Pattern.compile(String) method call followed by calls to the Matcher APIs instead of calling shorthand methods in string, such as matches(), replaceAll, and replaceFirst, especially when these matching or replacement methods are invoked repeatedly inside a loop. Repeated calls to String.matches() or any other regex-based method defined in the String API will compile the String regex pattern every time; this can be very time-consuming for a complex regex pattern.

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.