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); } }
split is faster, but complex separators which might involve look ahead, Regex is only option.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With