4

This question 40194 asks about work arounds to check and replace variable names which are invalid in a specific MMA function context. For that case testing using the function itself is the most reliable approach, but I'd like a more general method.

Is there a builtin function or a more general way to test syntax and validity?

One idea, if there are error messages, we can use Check:

varCheckQ[s_String]:=Check[SyntaxQ[Symbol[s]], False] // Quiet

varCheckQ/@{"1st","two wrds","no_good","al.most","ok"} (* {False, False, False, False, True} *)

Or, maybe try to match with unevaluated

varNameQ[s_String]:=!BooleanQ[Quiet@Symbol[s]==Unevaluated@Symbol[s]]

varNameQ/@{"1st","two wrds","no_good","al.most","ok"} (* {False, False, False, False, True} *)

These work, but don't seem very robust. Is there a utility function defined somewhere that already does this using MMA's rules?

xzczd
  • 65,995
  • 9
  • 163
  • 468
dionys
  • 4,321
  • 1
  • 19
  • 46

1 Answers1

5

There is the undocumented function Internal`SymbolNameQ:

Internal`SymbolNameQ /@ {"1st", "two wrds", "no_good", "al.most", "ok"}
 {False, False, False, False, True}
kglr
  • 394,356
  • 18
  • 477
  • 896
  • 1
    Internal`SymbolNameQ: Undocumented function that apparently identifies a string as a "symbol name." – dionys Sep 05 '20 at 13:45