5
expr = First@
  Level[Values@
    WolframLanguageData["Plot", 
     EntityProperty["WolframLanguageSymbol", 
      "DocumentationExampleInputs"]], {3}]

Plot[Sin[x], {x, 0, 6 Pi}]

But I find the Head of expr is RawBoxes

Head@expr
(* RawBoxes *)

And I cannot get the string like "Plot[Sin[x],{x,0,6 Pi}]"

ToString@expr
(* "RawBoxes[Cell[BoxData[RowBox[{Plot, [, RowBox[{RowBox[{Sin, 
[, x, ]}], ,, RowBox[{{, RowBox[{x, ,, 0, ,, RowBox[{6, Pi}]}], 
}}]}], ]}]], Input, ShowStringCharacters -> True]]" *)
yode
  • 26,686
  • 4
  • 62
  • 167

3 Answers3

4

Actually MakeExpression works. If you want to evaluate that expression,

expr//ToBoxes//MakeExpression//ReleaseHold

will work. If you want to get similar output as Wjx

(expr // ToBoxes // MakeExpression) /. ExpressionCell[a_, __] :> a
vapor
  • 7,911
  • 2
  • 22
  • 55
2

Will this help?

Cases[Hold[Plot[Sin[x], {x, 0, 6 Pi}]], ExpressionCell[cont_, ___] :> Hold@cont, Infinity]

{Hold[Plot[Sin[x], {x, 0, 6 [Pi]}]]}

A trick using Cases to extract stuffs in a Held Expression. Is this what you need? :)

Also, if your real application needs you to convert them into a string:

Cases[Hold[Plot[Sin[x], {x, 0, 6 Pi}]], 
  ExpressionCell[cont_, ___] :> ToString@Unevaluated@cont, 
  Infinity][[1]]

"Plot[Sin[x], {x, 0, 6 Pi}]"

Wjx
  • 9,558
  • 1
  • 34
  • 70
1

A solution that is not very satisfactory is to grab the argument of BoxData and turn that into an expression.

expr = First@
  Level[Values@
    WolframLanguageData["Plot", 
     EntityProperty["WolframLanguageSymbol", 
      "DocumentationExampleInputs"]], {3}]
FirstCase[expr, BoxData[data_]:>data,,Infinity]//ToExpression

(one can also use MakeExpression[#,StandardForm]& instead of ToExpression to get a held expression).

Bruno Le Floch
  • 1,959
  • 10
  • 23
  • I cannot very understand your FirstCase.Have you see this post? – yode Sep 02 '16 at 18:09
  • The goal is to extract the argument of BoxData in expr. The pattern BoxData[_] matches BoxData with any single argument; I've named that argument data. Then :> introduces a rule, whose right-hand side is data, meaning that I extract the argument I've named data. The empty argument (between commas) is the default value used in case BoxData[_] did not match anything in your expr, and the Infinity describes at which levels to operate. Contrarily to your other question here we are working with expressions and not just strings so no difficulty matching paired delimiters. – Bruno Le Floch Sep 02 '16 at 18:23