62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.ArrayList;
public class R {
/**
* @param args
*/
public static void main(String[] args) {
String[][] s = split("[a:ab,cde[],ee[ga]a],[a1:b1a[]aa,gg[]gs e:a g],[a2:b2:a[2] s[e]g]");
for (String[] ss : s)
System.out.println(ss[0] + "\t" + ss[1]);
}
private static String[][] split(String src) {
ArrayList<String[]> list = new ArrayList<String[]>();
int start = 0;
int n = 0;
String sub;
int index;
for (int i = 0; i < src.length(); i++) {
switch (src.charAt(i)) {
case '[':
if (++n == 1)
start = i + 1;
break;
case ']':
if (--n == 0) {
sub = src.substring(start, i);
index = sub.indexOf(':');
list.add(new String[] { sub.substring(0, index), sub.substring(index + 1) });
}
break;
}
}
String[][] s = new String[list.size()][];
list.toArray(s);
return s;
}
}
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
String s="[a:ab,cde[],ee[ga]a],[a1:b1a[]aa,gg[]gs e:a g],[a2:b2:a[2] s[e]g]";
String[] ss = split(s);
Entry[] entries = toEntries(ss);
for(Entry entry : entries) {
System.out.println(entry);
}
}
public static Entry[] toEntries(String[] strs) {
Entry[] entries = new Entry[strs.length];
for(int i = 0; i < strs.length; i++) {
int start = (strs[i].charAt(0) == '[' ? 1 : 0);
int end = (strs[i].charAt(strs[i].length() - 1) == ']' ? strs[i].length() - 1 : strs[i].length());
int idx = strs[i].indexOf(':');
if(idx < 0) {
entries[i] = new Entry(strs[i].substring(start, end), null);
} else {
entries[i] = new Entry(strs[i].substring(start, idx), strs[i].substring(idx + 1, end));
}
}
return entries;
}
public static String[] split(String str) {
if(str == null) {
return null;
}
if(str.length() == 0) {
return new String[0];
}
char[] chs = str.toCharArray();
List<String> list = new ArrayList<String>();
int s = 0, len = 0;
for(int i = 0, level = 0; i < chs.length; i++) {
if(chs[i] == ',' && level == 0) {
list.add(new String(chs, s, len));
len = 0;
s = i + 1;
continue;
}
len++;
if (chs[i] == '[') {
level++;
} else if (chs[i] == ']') {
level--;
}
}
list.add(new String(chs, s, len));
return list.toArray(new String[list.size()]);
}
public static class Entry {
private String key;
private String value;
public Entry() {
}
public Entry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "key=" + key + ", value=" + value;
}
}
}