Java split (), uses whole words containing a specific character as a delimiter

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

I want to use split() here, but I need the separator to be -4 . I do not 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 get

 parts[0] = "3 5 3" parts[1] = "2 3" 
+5
source share
3 answers

From what I mentioned in the comments, you can use -\\d+ to separate. He finds all the places where there is - followed by any number of digits. We can trim 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()); } 

Perfect demonstration

+7
source

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

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

Admittedly, this is a little circular movement, but it will be fast, easy, and will work.

+2
source

Using StringUtils you can do something like this

 public static void main(String[] args) { String splitMe="123-457"; String [] newArray=StringUtils.split(splitMe, "-4"); for (String val:newArray){ System.out.println(val.toString()); } } 

the output will be 123 for the 1st index and 57 for the second index

0
source

All Articles