java regexp for nested parenthesis

后端 未结 1 1824
臣服心动
臣服心动 2021-01-27 10:55

Consider the following java String:

String input = \"a, b, (c, d), e, f, (g, (h, i))\";

Can you help me to find a java regexp to obtain its 6 p

相关标签:
1条回答
  • 2021-01-27 11:32

    Don't try to use regex for this kind of task since regex in Java doesn't support recursion. Simplest solution would be writing your own parser which would count balance of ( and ) (lets call it parenthesis nesting level) and will split only on , if nesting level would be 0.

    Simple code for this task (which will also solve this problem in one iteration) could look like

    public static List<String> splitOnNotNestedCommas(String data){
        List<String> resultList = new ArrayList();
    
        StringBuilder sb = new StringBuilder();
        int nestingLvl = 0;
        for (char ch : data.toCharArray()){
            if (ch == '(') nestingLvl++;
            if (ch == ')') nestingLvl--;
            if (ch == ',' & nestingLvl==0){
                resultList.add(sb.toString().trim());
                sb.delete(0, sb.length());
            }else{
                sb.append(ch);
            }
        }
        if (sb.length()>0)
            resultList.add(sb.toString().trim());
    
        return resultList;
    }
    

    Usage:

    for (String s : splitOnNotNestedCommas("a, b, (c, d), e, f, (g, (h, i))")){
        System.out.println(s);
    }
    

    Output:

    a
    b
    (c, d)
    e
    f
    (g, (h, i))
    
    0 讨论(0)
提交回复
热议问题