需求是按逗号","来分割字符串,但这个逗号不能包含在一对括号中,比如
"(aa,bb) adf , asdfa,afd()"
应该返回
(aa,bb) adf 
 asdfa
afd()
这样
请教该如何写?

解决方案 »

  1.   

    这个在java中的正则做不到,因为java的正则不支持平衡组
      

  2.   

    可以有这个思路 先用正则匹配到括号内的逗号然后修改成任意不常见字符串比如!@#,然后用,split分组,再遍历数组每一项 如果string.contains("!@#")就replace成,
    关键就是第一步怎么找到括号内的,
    (?<=\(.*),(?=[^(]*\))可以匹配到这个逗号
    具体代码:
    string ss = "(aa,bb) adf , asdfa,afd()";
                string newstr = Regex.Replace(ss, @"(?<=\(.*),(?=[^(]*\))", "!@#");
                string[] list= newstr.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                List<string> temp = new List<string>();
                foreach (var item in list)
                {
                    temp.Add(item.Replace("!@#", ","));
                }
                string result = string.Join(",",temp);
      

  3.   

    好吧,自己写个土办法,先告一段落吧
    String input= "(aa,bb) adf , asdfa,afd()";
    List<Integer> l = new ArrayList<Integer>();
    int foundCount = 0;
    byte []arrInput = input.getBytes();
    for(int i=0;i<arrInput.length;i++){
    if(arrInput[i] == '('){
    foundCount++;
    }
    if(arrInput[i]==',' && foundCount>0){
    l.add(i);
    }
    if(arrInput[i]==')'){
    foundCount--;
    }
    }
    for(int index : l){
    arrInput[index] = '#';
    }
    String res = new String(arrInput);

    String []cols = res.split(",");
      

  4.   

    给你个思路,先用正则将所有()中的内容用list存起来,然后就将字符串的相应的内容用A,B,C等等先代替,然后split(","),然后再把A,B,C用list中的对应的换过来
      

  5.   

    开始匹配括号内的正则我写成这样(?<=\(.*),(?=.*\)) 结果把三个逗号都匹配到了 
    因为这个字符串最后是以“)”结尾的这个断言匹配到了字符串最后那个“)” 
    于是改成(?<=\(.*),(?=[^(]*\))让零宽正向先行断言的表达式内不允许出现“(”于是断言只会匹配到“bb)”
    貌似是贪婪的问题 但是不能使用“?”终止贪婪模式 这样写(?=.*?\))是不对的
      

  6.   

    取括号中的内容这样不行嘛  regex="\\((.+?)\\)"