Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.split pass in precompiled regex for performance reasons

Tags:

As the question states given the following code:

public class Foo {    public static void main(String[] args)    {            String test = "Cats go meow";            String[] tokens = test.split(" ");    } } 

is it possible to precompile that regex in the split function along the lines of this:

public class Foo {      Pattern pattern = Pattern.compile(" ");    public static void main(String[] args)    {            String test = "Cats go meow";            String[] tokens = test.split(pattern);    } } 
like image 740
Woot4Moo Avatar asked Feb 15 '13 19:02

Woot4Moo


People also ask

Is regex faster than string split?

split is faster, but complex separators which might involve look ahead, Regex is only option.

Is string split efficient?

String. split(String) won't create regexp if your pattern is only one character long. When splitting by single character, it will use specialized code which is pretty efficient. StringTokenizer is not much faster in this particular case.

Can we use regex in split a string?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

What does the string split regex method do?

Split(String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.


1 Answers

Yes, it is possible. Also, make pattern static so the static method main can access it.

public class Foo {      private static Pattern pattern = Pattern.compile(" ");    public static void main(String[] args)    {            String test = "Cats go meow";            String[] tokens = pattern.split(test);    } } 

According to the docs for the split method in String, you can use String's split or Pattern's split, but String's split compiles a Pattern and calls its split method, so use Pattern to precompile a regex.

like image 66
rgettman Avatar answered Oct 05 '22 18:10

rgettman