Иван Тонов Иван Тонов - 1 year ago 65
Java Question

Using .split() for multiple characters in Java

I'm trying to split an input by

".,:;()[]"'\/!? "
chars and add the words to a list. I've tried
, but both of them are returning empty elements in the list.

Additionally, I've tried
, which returns only words without any special characters that should go along with them (for instance, if one of the input words is "C#", it writes "C" in the list). Lastly, I've also tried to put all of the special chars above into the
.split("\\.,:;\\(\\)\\[]\"'\\\\/!\\? ")
, but this isn't splitting the input at all. Could anyone advise please?

Answer Source

split() function accepts a regex.

This is not the regex you're looking for .split("\\.,:;\\(\\)\\[]\"'\\\\/!\\? ")

Try creating a character class like [.,:;()\[\]'\\\/!\?\s"] and add + to match one or more occurences.

I also suggest to change the character space with the generic \s who takes all the space variations like \t.

If you're sure about the list of characters you have selected as splitters, this should be your correct split with the correct Java string literal as @Andreas suggested:


BTW: I've found useful

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download