Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using a Pattern to compile a regex for use instead of String.split()
import java.util.regex.Pattern;
public class MultilineStringSplitUsingRegex {
private static final Pattern pattern = Pattern.compile("\\r?\\n");
public static void main(String[] args) {
MultilineStringSplitUsingRegex m = new MultilineStringSplitUsingRegex();
String[] s1 = m.splitWithPattern();
String[] s2 = m.splitWithStringSplit();
}
/**
* Method makes use of a precompiled pattern that is not re-compiled repeatedly.
* This is better than using String.split()
*
*/
private String[] splitWithPattern() {
String str = "asdf\nqwer";
return pattern.split(str);
}
/**
* Example of expensive method. Regex pattern is created needlessly by String.split()
* (and also String.matches() method) every time this method is called.
* The java.util.regex.Pattern.compile() methods have a significant
* performance cost, and therefore should be used sensibly.
*
* @return
*/
private String[] splitWithStringSplit() {
String str = "asdf\nqwer";
return str.split("\\r?\\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.