Java – How to use java.util.regex.Pattern to split a String with a Regex

Here is a java example of how to split a string using a regular expression as the string delimiter. If this is to be done repeatedly (say in a loop) then using String.split() gets expensive because String.split() recompiles the regex pattern each time.

A better way of doing this is to precompile the regex and have the pattern as a static final at the top of the class.

   MultilineStringSplitUsingRegex.java


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");
	}
}

Pin It on Pinterest

Share This