Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a String in Java, ignoring multiple successive tokens

Tags:

java

regex

split

I'm trying to parse arguments for a command, but if I were to put multiple spaces in a row, String.split() will leave empty Strings in the result array. Is there a way I can get rid of this?

For example: "abc 123".split(" ") results in {"abc", "", "", "", "", "123"} but what I really want is {"abc", "123"}

like image 596
user322652 Avatar asked Oct 09 '10 04:10

user322652


1 Answers

Just use regex

"abc   123".split("\\s+");

Here \s is any whitespace character and \s+ is one or more consecutive whitespace characters.

like image 145
Nikita Rybak Avatar answered Sep 24 '22 00:09

Nikita Rybak