I have a String
that I want to split based on punctuation marks and whitespace. What should be the regex argument to the split()
method?
Code with some weirdness-handling thrown in: (Notice that it skips empty tokens in the output loop. That's quick and dirty.) You can add whatever characters you need split and removed to the regex pattern. (tchrist is right. The \s thing is woefully implemented and only works in some very simple cases.)
public class SomeClass {
public static void main(String args[]) {
String input = "The\rquick!brown - fox\t\tjumped?over;the,lazy\n,,.. \nsleeping___dog.";
for (String s: input.split("[\\p{P} \\t\\n\\r]")){
if (s.equals("")) continue;
System.out.println(s);
}
}
}
INPUT:
The
quick!brown - fox jumped?over;the,lazy
,,..
sleeping___dog.
OUTPUT:
The
quick
brown
fox
jumped
over
the
lazy
sleeping
dog
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