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);
}
}
Yes, it is possible. Also, make
patternstatic so the static methodmaincan access it.According to the docs for the
splitmethod in String, you can use String’ssplitor Pattern’ssplit, but String’ssplitcompiles aPatternand calls itssplitmethod, so usePatternto precompile a regex.