如何使用replace,substring,split等执行字符串操作

时间:2015-03-07 02:10:15

标签: java string replace split

我有像这样的字符串数据

string1 = ["car","house","boat"]["one","two","three","four"]["tiger","cat"]

我希望输出如下:

first : car,house,boat
second : one,two,three,four
third : tiger,cat

我应该如何对该字符串执行操作?

这是我目前的尝试:

result6 = string1.substring(1);
String[] parts = result6.split("\\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
result1 = "first : " + part1 + "\n" + "second : " + part2 + "\n" + "third : \n" + part3;

但这会让我错误输出。

1 个答案:

答案 0 :(得分:0)

您已在part1分配部分添加了part2part3result3而不是result1,4,5。而且我建议你根据][进行拆分,我只根据[进行拆分,你会在parts[0]得到一个空字符串。

String string1 = "[\"car\",\"house\",\"boat\"][\"one\",\"two\",\"three\",\"four\"][\"tiger\",\"cat\"]";
String parts[] = string1.split("\\]\\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
String result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
String result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
String result1 = "first : " + result3 + "\n" + "second : " + result4 + "\n" + "third : " + result5;
System.out.println(result1);

<强>输出:

first : car,house,boat
second : one,two,three,four
third : tiger,cat