String to Multidimensional Arrays
I have a string which represents a multidimensional array in the format: [[A, a], [B, b]]
Is the开发者_运维技巧re a easy way to convert this string into multidimensional arrays.
Though, for now I am just looking for the above solution the string itself is bit more complicated.
for example in [[A, a], [B, b]]
where A could be "This is a sample text, but could be complicated"
There is a high possibility that the delimiter comma exists in the text (which will be escaped)
Thanks, for any suggestions.
If you have control over the serialized string, I strongly suggest you look into JSON. It's an awesome format for things like this. It's lightweight, easy to read, and portable.
For example, from the link (note: the whitespace is not significant--this could all be on one line):
[
[0, -1, 0],
[1, 0, 0],
[0, 0, 1]
]
JSON provides a clean and safe mechanism for encoding strings in there, too. Click through for a lot of examples.
Your input format looks like a subset of JSON. Any of the Java JSON parsers listed on that page should be able to do what you want.
check this sample:
String[] x =
Pattern.compile("ian").split(
"the darwinian devonian explodian chicken");
for (int i=0; i<x.length; i++) {
System.out.println(i + " \"" + x[i] + "\"");
I haven't used java in a while, but to take a stab answering your question directly:
String[] myArray = input.split("(?<!\\),\s*\[");
String[][] myMDArray = new String[myArray.length][];
for (int i=0; i<myArray.length; i++) {
myArray[i].replaceAll("(?<!\\)[\[\]]", "");
myMDArray[i] = myArray[i].split("(?<!\\),");
}
Take it for what it's worth. Like others suggested, there are parsers that will do this with less effort and more flexibility.
精彩评论