Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Splitting String based on multiple delimiters

I essentially want to split up a string based on the sentences, therefore (for the sake of what I'm doing), whenever there is a !, ., ?, :, ;.

How would I achieve this with multiple items to split the array with?

Thanks!

like image 257
mino Avatar asked Feb 05 '12 14:02

mino


People also ask

How do I split a string with multiple separators in Java?

Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.

How do you split a string by multiple delimiters?

To split a string with multiple delimiters:Use the str. replace() method to replace the first delimiter with the second. Use the str. split() method to split the string by the second delimiter.

Can you use multiple delimiters in Java?

In order to break String into tokens, you need to create a StringTokenizer object and provide a delimiter for splitting strings into tokens. You can pass multiple delimiters e.g. you can break String into tokens by, and: at the same time. If you don't provide any delimiter then by default it will use white-space.

Can Split have multiple separators?

The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.


2 Answers

Guava's Splitter is a bit more predictable than String.split().

Iterable<String> results = Splitter.on(CharMatcher.anyOf("!.?:;"))
   .trimResults() // only if you need it
   .omitEmptyStrings() // only if you need it
   .split(string);

and then you can use Iterables.toArray or Lists.newArrayList to wrap the output results how you like.

like image 184
Louis Wasserman Avatar answered Nov 15 '22 23:11

Louis Wasserman


String.split takes a regex to split on, so you can simply:

mystring.split("[!.?:;]");
like image 29
Mat Avatar answered Nov 16 '22 00:11

Mat