如何逃避],[java中的序列?

时间:2015-03-27 04:46:02

标签: java regex java-ee

在java中编写代码时,我需要将字符串拆分为"],[" 。以下是我的代码。

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
            int i=0;
            String line;
            line = reader.readLine();
            String[] split = line.split("],[");
            StringBuilder sb = new StringBuilder();
            sb.append(split[0]);
            String joined = sb.toString();
            System.out.println(joined);

        } 

请在这里帮忙。

2 个答案:

答案 0 :(得分:3)

你必须逃离[。像:

line.split("\\],\\[");

您的代码将是:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
        int i=0;
        String line;
        line = reader.readLine();
        String[] split = line.split("\\],\\[");
        StringBuilder sb = new StringBuilder();
        sb.append(split[0]);
        String joined = sb.toString();
        System.out.println(joined);

    } 

答案 1 :(得分:1)

转义左方括号,因为[是正则表达式中的特殊元字符,表示字符类的开头。

String[] split = line.split("],\\[");
]之前没有字符类符号]的开头时,

[将匹配文字]符号。