简体   繁体   English

使用多个定界符分割查询字符串-Java

[英]Splitting query string using multiple delimiters - java

I would like to split these strings: 我想拆分这些字符串:

  1. /d/{?a} / d / {?一个}
  2. /a/b/{c}{?d} /A B C D}
  3. /a/b/c{?d} /A B C D}

into following list of segments: 分为以下细分列表:

  1. [d, {?a}] (this case is easy, just split using /) [d,{?a}](这种情况很简单,只需使用/拆分即可)
  2. [a, b, {c}, {?d}] [A B C D}]
  3. [a, b, c, {?d}] [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}. 在这种情况下,2和3.的最后一个字符串元素将是{c} {?d}和c {?d}。

What is the best approach to achieve all 1,2,3 at the same time? 同时实现所有1,2,3的最佳方法是什么?

Thanks. 谢谢。

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 '/'. 然后您可以用'/'分割它。 Eg: 例如:

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. 然后删除多余的“ /”,分割字符串并感到高兴。

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}. 如果您知道您的输入将始终是不同于{和}或{xyz}的任何字符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);
}

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 您将使用此正则表达式在split数组中获得空元素,但所有其他元素均被正确拆分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM