4
$\begingroup$

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?

$\endgroup$
5
$\begingroup$

There is the undocumented function Internal`SymbolNameQ:

Internal`SymbolNameQ /@ {"1st", "two wrds", "no_good", "al.most", "ok"}
 {False, False, False, False, True}
| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Internal`SymbolNameQ: Undocumented function that apparently identifies a string as a "symbol name." $\endgroup$ – dionys Sep 5 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.