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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.