2

The standard method for splitting string

String [] arr = s.split (regex);

Cuts the pieces out and removes the found regex. Is the a method that does the opposite?

NOTE: In my case there is nothing between the regex

Example:

Input

s = "320,192,6057,1,0,0:0:0:0:64,192,6327,128,0,7408:0:0:0:0:";

Output

arr[0] = "320,192,6057,1,0,0:0:0:0:";
arr[1] = "64,192,6327,128,0,7408:0:0:0:0:";
Cœur
  • 37,241
  • 25
  • 195
  • 267
King Natsu
  • 461
  • 4
  • 19
  • 1
    What do you call the opposite ? Strictly speaking, the opposite would be to remove all the "pieces" that do not match the regex, is that what you want ? – Dici Sep 04 '15 at 23:43
  • 1
    The question is unclear, you should just add an input/output example – Dici Sep 04 '15 at 23:46
  • @Dici Yes, but for now it doesn't matter if it'll be removed. Updated the Question for this important detail – King Natsu Sep 04 '15 at 23:46
  • What's the point? Just add the separator character back when you output each split. If it's important to not be added to the final element, then check the index isn't `(length() - 1)`. – aliteralmind Sep 05 '15 at 03:34
  • @aliteralmind Maybe it was wtong posting a highly simplyfied example. I'll edit that – King Natsu Sep 05 '15 at 03:40

1 Answers1

6

You can use a positive lookbehind regex to split your string like this:

(?<=;)

Working demo

IdeOne code

String[] arr = "1234:5678;8765,4321;".split("(?<=;)");
System.out.println(Arrays.asList(arr));
// arr[0] => 1234:5678;
// arr[1] => 8765,4321;

The trick of using regex lookaround (a positive lookbehind in this answer) is that lookarounds don't consume characters, therefore you won't lose the ; you want.

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • Sounds like it would work. Did you test it (with split) ? – Dici Sep 04 '15 at 23:54
  • 1
    @Dici yes, updated it IdeOne online demo – Federico Piazza Sep 04 '15 at 23:57
  • The sample in the Question was simplyfied. https://regex101.com/r/pT1lA4/2 in this test i use string like ones I'll use in my program. does it work with such regex? – King Natsu Sep 05 '15 at 00:40
  • @risingprogrammer you shouldn't change a question with a complete different meaning since answers get outdated. Imho, you should edit your question back to the original I answered, mark it as resolved and create another question in case you have more doubts. – Federico Piazza Sep 06 '15 at 02:00