Skip to content
Advertisement

How to get parameter names from a parametrized string?

What I’d like is:

JavaScript

I’ve looked through string.Template, it does only substitution.

Is there a standard library way to do this? Because in case of regex, there would have to be a check if $smt is actually a valid Python variable name and so on.

Advertisement

Answer

string.Template, or one of its subclasses, stores the compiled regex that will be used to find identifiers to replace as the pattern class attribute. Therefore you can do:

JavaScript

The groups in the result are:

  • escaped (e.g. $$ -> "$");
  • named (e.g. $identifier -> "identifier");
  • braced (e.g. ${noun}ification -> "noun"); or
  • invalid (“any other delimiter pattern (usually a single delimiter)”, e.g. $ -> "").

For your purposes, therefore, you probably want:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement