Tag Archives: pattern

Regexp-related methods of String

by Mikhail Vorontsov

java.lang.String has several methods, which are actually shortcuts for various java.util.Pattern/Matcher methods. These are

  • matches(String)
  • replaceAll(String, String), replaceFirst(String, String)
  • split(String), split(String, int)

These methods have 2 performance drawbacks:

  • they create and compile Pattern objects internally for each call
  • they may be used for simple cases, when manual parsing is absolutely appropriate

For example, matches(String) method is implemented as Pattern.matches(regex, this), which tries to match current string (this) against the given regex. Pattern.matches is defined as Pattern.compile(regex).matcher(input).matches()

All other String regex methods look similar: compile a temporary Pattern, create a Matcher for current String and call required method on the Matcher object. This is appropriate if you are using these String methods just once or rarely, but it is better to avoid them if you are calling regex methods for each piece of data you are processing.

Continue reading