# Importing data surrounded by Square brackets

I have a big one line data file with a list of integers which are in the following format:

[[1 4 5 6 2] [9 8 7 4 7] [....]],[[...] .....[...]],.....]]


I have been trying Import but what I get is

{{[[1,4,5,6,2],[9,8,7,4,7],[....]],[[...] .....[...]],.....]]}}


The problem is that I can not replace the "[" and "]" by "{" and "}" respectively.

How I could a list of lists with brackets?

Thanks regards

• I guess something like ImportString["[[1 4 5 6 2] [9 8 7 4 7] [10 3 1 0 5]],[[3 0 9 1 7] [5 6 11 1 7] [3 0 2 0 1]]", "Table", "FieldSeparators" -> {" "}, "IgnoreEmptyLines" -> True, "LineSeparators" -> {",", "[", "]"}]? – J. M. will be back soon Mar 31 '17 at 13:26
• Hi, I can not copy-paste the content of the file into ImportString command of your example because there are mores than 300 000 integers. Also, this example gives {{1,4,5,6,2},{ }, [9 8 7 4 7] . – user1993416 Mar 31 '17 at 13:44
• import the whole thing as string then, ToExpression[StringReplace[instring, {" " -> ",", "[" -> "{", "]" -> "}"}]] (You may need an extra pair of { } around the whole thing ) Is this matlab output by the way? – george2079 Mar 31 '17 at 13:46
• The idea is to use Import[filename, "Table", options] on your end, where you make the necessary replacements. – J. M. will be back soon Mar 31 '17 at 13:49
• I have tested the two alternatives work fine. Thank you very much @J.M and – user1993416 Mar 31 '17 at 13:56

ToExpression[
StringReplace["[[1 4 5 6 2] [9 8 7 4 7]]", {" " -> ",", "[" -> "{", "]" -> "}"}]]
(* {{1, 4, 5, 6, 2}, {9, 8, 7, 4, 7}} *)

• i just realized george2079 wrote the same answer in the comments – Ali Hashmi Mar 31 '17 at 16:19

This is what you after?

string="[[1 4 5 6 2] [9 8 7 4 7] [10 3 1 0 5]],[[3 0 9 1 7] [5 6 11 1 7] [3 0 2 0 1]]";
ImportString[StringReplace[#,Whitespace->","],"RawJSON"]&/@StringSplit[string,","]


{{{1,4,5,6,2},{9,8,7,4,7},{10,3,1,0,5}},{{3,0,9,1,7},{5,6,11,1,7},{3,0,2,0,1}}}

• +1, and a suggestion: it'll be more robust if you replace " " with Whitespace. – Szabolcs Mar 31 '17 at 15:30
• @Szabolcs Good suggestion,I have updated that.Thanks. – yode Mar 31 '17 at 15:34

You could use something like this if your data is not too large:

terp = Interpreter[
DelimitedSequence[
DelimitedSequence["Number", {"[", Whitespace, "]"}],
{"[", Whitespace, "]"}
]
]

terp["[[1 2] [3 4]]"]
(* {{1, 2}, {3, 4}} *)


You can add another layer of DelimitedSequence if you have several such expressions separated by commas.

Unfortunately, this method of parsing is quite slow.