如何分割括号内有分隔符的字符串?
就是要无视掉括号中的分隔符
比如
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 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
*/
}
}
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);
}
}
然后从头判断是否包含相等的 ( 和 ) ,相等就是ok的,不相等就把后面的链接进来直到相等为止,不知道不行不可行。
import java.util.regex.Pattern;public class Test
{
public static void main(String[] args)
{
String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd";
Pattern p = Pattern.compile("(\\w\\(\\d,\\(\\d,\\d\\),\\d\\)\\w),(\\w{2}\\(\\d,\\d\\)),(\\(\\d,\\d\\)\\w{2})");
Matcher m = p.matcher(str);
if (m.matches())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
}
}
试一下行不行
/*
* how to get:
*
* 1. a(1,(2,3),4)b
* 2. bc(4,5)
* 3. (6,7)cd
*/
public static void main(String[] args) {
String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd";
String arr[] = str.split(",(?=[^)(]*?(\\([^)(]*?\\),?)+[^)(]*$)");
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
//改一个bug
public 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]);
}
}
源码:
public class Aotian16 { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd";
str = str.replaceAll(",", "");
System.out.println(str);
}}
import java.util.List;public class HelloWorld {
public static void main(String[] args) {
String str = "a(1,(2,3),4)b,bc(4,5),(6,7)cd,cf(1,1,((1,1,)),2,2,2)";
char[] cs = str.toCharArray();
int count =0 ;
for(char c:cs){
if ((c == ',') && ( count == 0 ))
{
if ( count == 0 ) System.out.println();
}
else {
System.out.print(c);
}
if ( c == '(') count++;
if ( c == ')') count--;
}
}}
打印结果:
a(1,(2,3),4)b
bc(4,5)
(6,7)cd
cf(1,1,((1,1,)),2,2,2)