Regular expression matching always comes with the cost of pattern matching. In case the pattern is not precompiled then the the expression parsing happens every time the code is invoked.
Some of Java String methods use regular expressions e.g. matches(...), replaceFirst(...), replaceAll(...) and split(...). These methods actually use Pattern matching library methods internally however these patterns are parsed every time these methods are invoked. The performance impact is significant if these methods are called too frequently or in high traffic zone.
Java library provides Pattern package which could be used to precompile the regular expressions.
Here are equivalent code which uses the precompiled pattern.
1) String.split(regex)
[java]
private static final String regex = "\\.";
String[] keys = str.split(regex);
[/java]
[java]
import java.util.regex.Pattern;
private static final Pattern myPattern = Pattern.compile(regex);
String[] keys = myPattern.split(str);
[/java]
2) String.replace*(regex...)
2.1) replaceFirst() - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceFirst(java.lang.String, java.lang.String)
[java]
str.replaceFirst(regex, repl) yields exactly the same result as the expression
"Pattern.compile(regex).matcher(str).replaceFirst(repl)""
[/java]
[java]
private static final String regex = "\\.";
private static final Pattern myPattern = Pattern.compile(regex);
myPattern.matcher(str).replaceFirst(repl);
[/java]
2.2) replaceAll() - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
[java]
str.replaceAll(regex, repl) yields exactly the same result as the expression
"Pattern.compile(regex).matcher(str).replaceAll(repl)""
[/java]
[java]
private static final String regex = "\\.";
private static final Pattern myPattern = Pattern.compile(regex);
myPattern.matcher(str).replaceAll(repl);
[/java]
3) matches(regex) - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)
[java]
str.matches(regex) yields exactly the same result as the expression
"Pattern.matches(regex, str)"
[/java]
[java]
private static final String regex = "\\.";
private static final Pattern myPattern = Pattern.compile(regex);
myPattern.matches(regex, str);
[/java]
No comments:
Post a Comment