我不知道正則表達式是能夠做這樣的東西自己。這裏是一個辦法做到這一點,但:
// data string
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
System.out.println(input);
// char that can't ever be within the data string
char tempReplacement = '#';
// escape strings containing commas, e.g "hello, world", ["x, y", 42]
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
// while there are "[*,*]" substrings
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
// replace the nested "," chars by the replacement char
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
// split the string by the remaining "," (i.e. those non nested)
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
// replace all the replacement chars by a ","
s = s.replaceAll(tempReplacement + "", ",");
s = s.trim();
output.add(s);
}
// syso
System.out.println("SPLIT:");
for(String s : output) {
System.out.println("\t" + s);
}
輸出:
"aa", "a, aa", ["bb", ["1", "2"]], [cc], ["dd", ["5"]]
SPLIT:
"aa"
"a, aa"
["bb", ["1","2"]]
[cc]
["dd", ["5"]]
PS:代碼似乎複雜的「事業評論。這裏是一個更簡潔的版本:
public static List<String> split(String input, char tempReplacement) {
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
output.add(s.replaceAll(tempReplacement + "", ",").trim());
}
return output;
}
電話:
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
List<String> output = split(input, '#');
你試圖解析JSON?如果是這樣,有Java的庫可以做到這一點。 –
@DelanAzabani不幸的是它不是JSON。 –
不幸的是,這隱含地要求使用括號匹配(以確保您匹配正確的右括號),這通常不能用正則表達式來完成。但是,如果您知道括號最多可嵌套2或3層,則可以。是這樣嗎? – huon