Pregunta

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?

¿Fue útil?

Solución

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

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

Otros consejos

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top