简体   繁体   中英

How to escape ],[ sequence in java?

While writing code in java, I need to split string with "],[" . Below is my code.

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);

        } 

Please help here.

You have to escape the [ . Like:

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

Your code would be:

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);

    } 

Escape the opening square bracket because [ is a special meta character in regex represents the start of a character class.

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

] will match a literal ] symbol when there is no start of the character class symbol [ exists before ] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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