Split a String based on regex

后端 未结 4 881
情歌与酒
情歌与酒 2020-12-17 18:55

I have a string that needs to be split based on the occurrence of a \",\"(comma), but need to ignore any occurrence of it that comes within a pair of parentheses. For exampl

4条回答
  •  别那么骄傲
    2020-12-17 19:29

    One simple iteration will be probably better option then any regex, especially if your data can have parentheses inside parentheses. For example:

    String data="Some,(data,(that),needs),to (be, splited) by, comma";
    StringBuilder buffer=new StringBuilder();
    int parenthesesCounter=0;
    for (char c:data.toCharArray()){
        if (c=='(') parenthesesCounter++;
        if (c==')') parenthesesCounter--;
        if (c==',' && parenthesesCounter==0){
            //lets do something with this token inside buffer
            System.out.println(buffer);
            //now we need to clear buffer  
            buffer.delete(0, buffer.length());
        }
        else 
            buffer.append(c);
    }
    //lets not forget about part after last comma
    System.out.println(buffer);
    

    output

    Some
    (data,(that),needs)
    to (be, splited) by
     comma
    

提交回复
热议问题