2

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.

Budzu
  • 173
  • 2
  • 12
  • What have you tried? Would /a/b/c{?d be split as [a, b, c{?d] (i.e. because of the missing })? How would you like [a, b, c, {de{f}g}] to be split (i.e. nested {})? Are you having only {} or also () or [], etc.? – Lucia Pasarin Aug 25 '15 at 21:50
  • @LuciaPasarin: thanks for your suggestion. – Budzu Aug 26 '15 at 13:07
  • How to achieve also another case like this (all the other three cases must work as well)? /a/b?c=123 => [a, b, c=123] Many thanks again. – Budzu Aug 26 '15 at 19:54
  • I got it: Regular expression: "(/)|(?=\\{\\?)|(?<!\\{)\\?" should work. – Budzu Aug 26 '15 at 19:59

3 Answers3

1

In the first case it's splitting. But in the rest cases it's parsing. You have to parse a string first and then split it. Try to add '/' right before every '{' and after every '}'. And then you can split it by '/'. E.g.:

Before parsing:

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

After parsing:

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

Then remove excessive '/', split the string and be happy.

Maxwellt
  • 126
  • 5
1

Here is some simple way of solving it in case you know your input is always going to be either any chars xyz different than { and } or {xyz}. In case you could have any other input, this would require some modifications:

String[] arr = input.split("/");
List<String> result = new ArrayList<>();

for (String elem : arr) {
    int lastCut = 0;
    for (int i = 0; i < elem.length(); i++) {
        if (elem.charAt(i) == '{' || elem.charAt(i) == '}') {
            if (i > 0) {
                String previousElem = elem.substring(lastCut, i);
                result.add(previousElem);
            }
            lastCut = i;
        }
    }
    if (lastCut < elem.length() - 2)
    String lastElem = elem.substring(lastCut + 1, elem.length());
    result.add(lastElem);
}
Lucia Pasarin
  • 2,268
  • 1
  • 21
  • 37
1

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

Frithjof Schaefer
  • 1,135
  • 11
  • 22