Java String.split pass in precompiled regex for performance reasons
java, performance, regex
Solution
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.
Problem
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); } } ```