Question

I'm trying to load a string into an array, removing all whitespace and punctuation. The problem is, if I have two delimiters in a row, it leaves a blank in the array.

What I have:

String[] temparray =inputstr.split("\\s+|,|;|\\(|\\)|, ");

Example:

inputstr = "I bought bread, eggs, and milk"

It outputs as:

I
bought
bread

eggs

and
milk

Anyone know how to keep the spaces after the commas from being loaded into the array?

Was it helpful?

Solution

You could use a character class to group all the separator characters

String[] temparray = inputstr.split("[\\s,;()]+");

OTHER TIPS

You can combine the two cases for "comma" and "comma followed by space" by using a ? metacharacter to indicate "optional".

I've replaced , with , ? (comma-space-question mark). This way the space is matched as part of the delimiter.

//                           space here ---v
String[] temparray = inputstr.split("\\s+|, ?|;|\\(|\\));

Printing each element of the array:

I
bought
bread
eggs
and
milk
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top