Last active
December 5, 2018 10:35
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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