public static void main(String[] args){
String testStr = "Test test. Test 2. Test3?";
String[] newStr = testStr.split(".?");
System.out.print(newStr[0]);
}
I get an Array Index Out of Bounds exception running this, and the length of newStr is 0. I want to break the sentence up into tokens on “.” and “?”. What error am I making?
String#splittakes a regular expression as a parameter to split..and?have special meaning in regular expressions.You can use character class to split on either of them:
Inside a character class you don’t need to escape them, as special characters lose meaning inside character class.
If you use it with normal pipe
|, you need to escape it: –UPDATE: – If you want to preserve your delimiters: