Search code examples
javastringsplitguavasplitter

Splitting query string using multiple delimiters - java


I would like to split these strings:

  1. /d/{?a}
  2. /a/b/{c}{?d}
  3. /a/b/c{?d}

into following list of segments:

  1. [d, {?a}] (this case is easy, just split using /)
  2. [a, b, {c}, {?d}]
  3. [a, b, c, {?d}]

For the other cases, splitting using / will not get the result that I wanted. In which case, the last string element of 2. and 3. will be {c}{?d} and c{?d}.

What is the best approach to achieve all 1,2,3 at the same time?

Thanks.


Solution

  • try to solve the problem with a regex. This might be a script to start with:

    String regex = "(/)|(?=\\{)";
    String s =  "/a/b/{c}{?d}";
    String[] split = s.split(regex);
    

    you will get empty elements in the split array with this regex, but all other elements are splitted correctly