0

I was wondering what's the best approach to keep the delimiter with the aftermath String after its split("-").

So here is the code:

String word = "abc -def ghi -jkl -mno pqr";
String[] strArr= null;
strArr = word.split("-");
...
here we iterate through array     

it will print:

abc
def ghi
jkl
mno pqr

but I want to keep the delimiter and it should look something like:

abc
-def ghi
-jkl
-mno pqr

One way is, while iterating, to concatenate the "-" delimiter, but I was wondering if there is a better way.

Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
  • The delimiter actually seems to be the space in your example – fge Oct 29 '14 at 20:21
  • Depends: what's the correct output with input `"abc def -ghi -jkl"`? – ajb Oct 29 '14 at 20:24
  • @ajb there might be a time where there could be a space in between strings without delimiter which is why I specifically want it with `"-"` delimiter. – Simple-Solution Oct 29 '14 at 20:27
  • @Simple-Solution Yep, thought so. I think splitting on a lookahead is what you want. If you don't want to preserve the spaces before the `-`, then either `split(" +(?=-)")` or `split(" *(?=-)")`, depending on whether you want `-` with _no_ spaces before it to be a delimiter. – ajb Oct 29 '14 at 20:32
  • @ajb I want it with no spaces before if that what your asking. – Simple-Solution Oct 29 '14 at 20:35
  • @ajb also can you explain what this part is telling splitter `split(" +(?=-)")`? – Simple-Solution Oct 29 '14 at 20:40
  • 1
    The delimiter is one or more spaces, followed by a _lookahead_ pattern that matches `-`. The effect is that the delimiter will match a space, or spaces, that is _followed by_ a hyphen, but the hyphen itself doesn't become part of the delimiter because of _lookahead_. The spaces do become the delimiter, so they get removed when the resulting substrings are created. But the hyphen isn't part of the delimiter so it gets to stay. – ajb Oct 29 '14 at 20:48

1 Answers1

4

You can split on the space :

strArr = word.split(" ");
Eran
  • 387,369
  • 54
  • 702
  • 768