我对Java还比较陌生。 我想知道是否有更简单但高效的方法来实现以下字符串分割。我尝试使用模式和匹配器,但并没有得到我想要的结果。
"{1,24,5,[8,5,9],7,[0,1]}"
要被分割成:
1
24
5
[8,5,9]
7
[0,1]
这是一段完全错误的代码,但我还是要发布它:
String str = "{1,24,5,[8,5,9],7,[0,1]}";
str= str.replaceAll("\\{", "");
str= str.replaceAll("}", "");
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(str);
String[] test = new String[10];
// String[] _test = new String[10];
int i = 0;
String[] split = str.split(",");
while (matcher.find()) {
test[i] = matcher.group(0);
String[] split1 = matcher.group(0).split(",");
// System.out.println(split1[i]);
for (int j = 0; j < split.length; j++) {
if(!split[j].equals(test[j])&&((!split[j].contains("\\["))||!split[j].contains("\\]"))){
System.out.println(split[j]);
}
}
i++;
}
}
假设有一个字符串格式,类似于{a,b,[c,d,e],...}的格式。我想列举出所有的内容,但方括号中的内容应该被表示为一个元素(就像数组一样)。
{
/}
分隔列表”,那么编写一个小解析器或正则表达式来匹配元素将不会很难。 - Joshua Taylor