Last active
November 16, 2017 22:55
-
-
Save gvoysey/03ed843231670d51cccab1f829ac5fc8 to your computer and use it in GitHub Desktop.
munges a string so that it is a valid matlab variable name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| def known_bad(x): | |
| """provide string substitutions for common invalid tokens, or remove them if not found.""" | |
| return {' ': '_', | |
| '(': '_lp_', | |
| ')': '_rp_', | |
| '-': '_minus_', | |
| '/': '_div_', | |
| ';': '_sc_' | |
| }.get(x, '') | |
| def sanitize_name(namestr): | |
| """A valid variable name starts with a letter, followed by letters, | |
| digits, or underscores, and cannot be one of several reserved words.""" | |
| keywords = {'break', 'case', 'catch', 'classdef', 'continue', 'else', 'elseif', 'end', 'for', 'function', | |
| 'global', 'if', 'otherwise', 'parfor', 'persistent', 'return', 'spmd', 'switch', 'try', 'while'} | |
| if namestr in keywords: | |
| raise NameError(f'{namestr} is not a valid matlab name') | |
| # match whatever isn't alphanumeric or underscore | |
| for illegal in re.compile(r'([^A-Za-z0-9_])').findall(namestr): | |
| namestr = namestr.replace(illegal, known_bad(illegal)) | |
| if not namestr[0].isalpha(): | |
| namestr = f'm_{namestr}' | |
| return namestr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment