如何使用String.split在方括号之间提取文本

Dev*_*hka 2 java text-parsing

我的文字包含以这种格式表示的标签:[text other text].

我想用方括号拆分字符串作为分隔符,但是:

String.split("\\[|\\]");
Run Code Online (Sandbox Code Playgroud)

这不会给出预期的结果.

我怎样才能做到这一点?

And*_*hev 8

我不确定是否可以这样做split().通过模式查找和[^\\]]+(您的模式中的"所有符号直到结束括号"),这非常简单:

public static void main(String[] args) {
    String line = "xx [text other text], [jili u babusi dva veselikh gusya], " +
        "[a granny there was having two gay gooses] zz";

    Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(line);

    List<String> tags = new ArrayList<>();

    int pos = -1;
    while (matcher.find(pos+1)){
        pos = matcher.start();
        tags.add(matcher.group(1));
    }

    System.out.println(tags);
}
Run Code Online (Sandbox Code Playgroud)