About the first section: This simulates the behavior of Mathematica a bit more closely than Kuba's answer, creating an additional RowBox. However, the choice of how general the different aspects of the solution are may be a bit odd. Kuba's answer feels cleaner.
Use the OPs definition of str. The following will generate an input cell where the comments are (still) present as comments.
store[str_String] := (Sow[str]; token);
CellPrint[Cell[#, "Input"]] &@
BoxData[
ReplacePart[#[[1]],
MapThread[
Rule, {Position[#[[1]], "token"],
Composition[RowBox, List] /@ #[[2, 1]]}]] &@
Reap[ToBoxes@Map[Composition[store, ToString], str, {2, 2}]]]
Format preserving alternative
Suppose we start with the input cell
str =
{{{"8.0,1034(*g opx ksp pl ilm liq q *)"}, {"8.0,1035(*g opx \
ksp pl ilm liq q *)"}}, {{"8.0,886(*g opx ksp pl ilm liq q *)"}}}
We can give this a celltag by putting our cursor in the cell and doing Cell>Show Expression from the menu. The resulting cell will be the same as the cell printed by
Cell[BoxData[
RowBox[{"str", "=",
RowBox[{"{",
RowBox[{
RowBox[{"{",
RowBox[{
RowBox[{"{",
"\"\<8.0,1034(*g opx ksp pl ilm liq q *)\>\"", "}"}],
",",
RowBox[{"{",
"\"\<8.0,1035(*g opx ksp pl ilm liq q *)\>\"",
"}"}]}], "}"}], ",",
RowBox[{"{",
RowBox[{"{",
"\"\<8.0,886(*g opx ksp pl ilm liq q *)\>\"", "}"}],
"}"}]}],
"}"}]}]], "Input", CellTags -> {"targetCell"}] // CellPrint
We can now do
NotebookRead[Cells[CellTags -> "targetCell"]] /.
x_String?(StringMatchQ[#,
"\"*" ~~ Verbatim["(*"] ~~ ___ ~~ Verbatim["*)\""]] &) :>
StringTake[x, {2, -2}] // CellPrint
to get a cell that is formatted in the same way as the cell with CellTag "targetCell", except for any formatting that may occur inside strings.
Format ignoring option using strings
Mr.Wizard hinted at a solution using strings, and Rm-rf gave the main code for this
CellPrint[Cell[#, "Input"]] &@
First@MathLink`CallFrontEnd@
UndocumentedTestFEParserPacket[ToString[str], False]
Which seems nice for this question, especially as having comments in strings hints at the expression str being the result of some Import command by Mathematica, or that this expression is at least generated in some way. In this case you don't care about existing formatting and in case of Import maybe it is an option to do all parsing by UndocumentedTestFEParserPacket
. Who knows
ToString[NotebookRead[Cells[CellTags -> "targetCell"][[1]]][[1, 1]], InputForm]
, but I guess that should feel indirect. $\endgroup$