문제

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?

도움이 되었습니까?

해결책

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

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top