拆分递归组

时间:2014-02-07 05:42:08

标签: java regex

我有这种格式的字符串: a,b,c[a,b,c[a]],d

我想最终得到的是什么(

a
b
c.a
c.b
c.c.a
d

有关如何处理此任务的任何建议吗?

1 个答案:

答案 0 :(得分:1)

这是使用堆栈的可能解决方案。 (实施了Avlin Bunk的评论。)

public static Iterable<String> split(String s) {
    List<String> result = new LinkedList<String>();
    Stack<String> stack = new Stack<String>();
    Pattern pattern = Pattern.compile("[,\\[\\]]|.+?");
    Matcher matcher = pattern.matcher(s);

    stack.push("");
    while (matcher.find()) {
        String token = matcher.group();
        if (token.equals("[")) {
            stack.push("");
        } else if (token.equals("]")) {
            if (! stack.peek().isEmpty())
                result.add(join(".", stack));
            stack.pop();
            stack.pop();
            stack.push("");
        } else if (token.equals(",")) {
            if (! stack.peek().isEmpty())
                result.add(join(".", stack));
        } else {
            stack.pop();
            stack.push(token);
        }
    }
    if (! (stack.isEmpty() || stack.peek().isEmpty()))
        result.add(join(".", stack));
    return result;
}

public static String join(String sep, Iterable<String> it) {
    // Return it[0] + sep + it[1] + sep + .... + it[lastIndex]
    String joined = "";
    boolean first = true;

    for (String s : it) {
        if (first)
            first = false;
        else
            joined += sep;
        joined += s;
    }
    return joined;
}

示例用法:

String text = "a,b,c[a,b,c[a]],d";
for (String s : split(text))
    System.out.println(s);

请参阅Demo run

Same solution in PythonRecursive solution in Python