括号内有分隔符的字符串分割
如何分割括号内有分隔符的字符串?
就是要无视掉括号中的分隔符
比如
public class HelloWorld { public static void main(String[] args) { String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd"; /* * how to get: * * 1. a(1,(2,3),4)b * 2. bc(4,5) * 3. (6,7)cd */ }}
public static void main(String[] e) { String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd"; char[] cs = str.toCharArray(); int layer = 0; List<Integer> indexs = new ArrayList<Integer>(); List<String> strs = new ArrayList<String>(); for(int i = 0; i < cs.length; i++){ if(layer == 0 && ',' == cs[i]){ indexs.add(new Integer(i)); } if('('== cs[i]){ layer++; }else if(')'== cs[i] && layer > 0){ layer--; } } for(int i = 0; i < indexs.size(); i++){ if(i == 0){ strs.add(str.substring(0, indexs.get(i))); }else{ strs.add(str.substring(indexs.get(i - 1) + 1, indexs.get(i))); } if( i == indexs.size() - 1){ strs.add(str.substring(indexs.get(i) + 1)); } } for(String ss : strs){ System.out.println(ss); } }
[解决办法]
//改一个bugpublic static void main(String[] args) { String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd,qwqw"; String arr[] = str.split(",(?=[^)(]*?(\\([^)(]*?\\),?)*[^)(]*$)"); for(int i=0;i<arr.length;i++){ System.out.println(arr[i]); } }