2

regarding this topic: https://stackoverflow.com/questions/4416425/how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j#=

I want to know how to make from this string:

String string1="Ram-sita-laxman";

seperation like this:

["Ram", "-" , "sita", "-",  "laxman"]

How can i achieve that?

Community
  • 1
  • 1
tryingHard
  • 1,794
  • 4
  • 35
  • 74

1 Answers1

4

You need to use look ahead and look behind like following

    String string1="Ram-sita-laxman";
    System.out.println(Arrays.toString(string1.split("((?<=-)|(?=-))")));

In this the output will be [Ram, -, sita, -, laxman]

Notice that while the delimiter is there but not everything is in quotes cause it can't be unless you add them yourself in the array

Hope this helps.

Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34
  • If i make `string1.split("((?<=and|or)|(?=and|or))");` i get split by words "**and**" and "**or**" i want additionaily split by brackets "**(**" and "**)**" how can i make it? Thank you for your response :) – tryingHard Nov 20 '15 at 03:04
  • @yami You already have the elements in an array in the answer I had givem. You can just loop the array and add the double quotes to each element – Balwinder Singh Nov 20 '15 at 03:15
  • Sir, i asked kind of a different question now. not about quotes `" "` But how to split string in 1 operation by 4 strings: **"and"** **"or"** **"("** **")"** Let's say starting string was: `(a=1 and b=2) or(a=3 and b=4)` – tryingHard Nov 20 '15 at 11:12