Skip to content

Instantly share code, notes, and snippets.

@lizettepreiss
Last active December 5, 2018 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizettepreiss/aa346b649843892b3b57ce8811d6b354 to your computer and use it in GitHub Desktop.
Save lizettepreiss/aa346b649843892b3b57ce8811d6b354 to your computer and use it in GitHub Desktop.
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