简体   繁体   中英

java extract elements separated by comma in a String

i have a problem to extract a particular kind of element in a String. The string is like this:

String input = [[2,3],[4,5],'hello',3,[3,[5,[6,7]]]],'hi',3

I'm using the split method to split the three elements of the string above, but i cannot find a regex that allows me to consider only the commas outside the list.

In a precedence question was suggested me to use this regex:

,(?![^\[]*[\]]) 

This regex works in some cases, but not in the case above. I tried in different ways, but honestly i have not found a solution.

Using regex, you just can achieve it using regex recursion but java's standard regex library doesn't support recursion.

But you can achieve what you are trying to do doing something similar to this:

String input = "[[2,3],[4,5],'hello',3,[3,[5,[6,7]]]],'hi',3";
String[] splited = input.split(",");
List<String> result = new ArrayList<String>();

int brackets = 0;
String aux = "";
for (String string : splited) {
    char[] word = string.toCharArray();

    // count the brackets
    for (char c : word) {
        if(c=='['){
            brackets++;
        }
        else if(c==']'){
            brackets--;
        }
    }

    aux = aux + string;

    // if all opened brackets are closed
    if (brackets == 0) {
        result.add(aux);
        aux = "";
    } else {
        aux = aux + ",";
    }
}
// the list 'result' contains 3 elemets. Each one is one element separeted by comma

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