Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split(), use whole word containing a specific character as separator

Tags:

java

string

regex

String string = "3 5 3 -4 2 3 ";

I want to use split() here but I need to a separator to be -4. I don't know which numbers are negative and I need to use split to group positive numbers in separate arrays.

Is it possible?

Edit:

I want to use:

String[] parts = string.split(????);

and receive

parts[0] = "3 5 3"
parts[1] = "2 3"
like image 343
dddeee Avatar asked Jun 03 '16 19:06

dddeee


2 Answers

From what I mentioned in comments, you can use -\\d+ for splitting. It finds all the places where there is - followed by any number of digits. We can trim the array elements later if we want

Java Code

String Str = new String("3 5 3 -4 2 3");
String[] x = Str.split("-\\d+");

for (String retval: x){
   System.out.println(retval.trim());
}

Ideone Demo

like image 98
rock321987 Avatar answered Sep 24 '22 17:09

rock321987


You can use the replace method to search for a given string (in this case, -4) and replace it with a delimiter of your choice, perhaps a pipe-bar line (|). Then you can use the split method and use the delimiter that's now inserted to split your array.

string = string.replace(replaceString, "|");
string[] parts = string.split('|');

Admittedly this is a little roundabout, but it's quick, easy, and will work.

like image 22
Jeremy Kato Avatar answered Sep 24 '22 17:09

Jeremy Kato