Effacer les filtres
Effacer les filtres

Which characters are replaced by matlab.lan​g.makeVali​dName?

1 vue (au cours des 30 derniers jours)
Jannik
Jannik le 17 Mai 2024
Commenté : Jannik le 21 Mai 2024
Function matlab.lang.makeValidName does 2 things:
  1. first, it checks the input string for special characters which are not allowed to be contained in identifiers and replaces those (e.g. with "")
  2. second, it checks the length of the input string with possibly replaced characters, and if is too long, it truncates the string.
However, I would like the function to check only for special characters, not for length.
One option would be to use "strrep", but then I would like to generate the list of characters which are replaced by matlab.lang.makeValidName to be consistent with makeValidName.

Réponse acceptée

Adam Danz
Adam Danz le 17 Mai 2024
Modifié(e) : Adam Danz le 20 Mai 2024
matlab.lang.makeValidName uses isvarname to determine if the string is a valid variable name. The doc page for isvarname states that a valid variable name has the following requirements
  • begins with a letter
  • contains not more than namelengthmax characters (run that function to return max name length)
  • includes only letters, digits, and underscores.
So the regular expression to replace characters that aren't letters, digits, or underscores would be
validChars = '[^a-zA-Z_0-9]';
strClean = regexprep(str, validChars, '_')
where the caret symbol is used to match any character not contained within the character vector.
Limitations
  • This does not check that the leading character is a letter.
  • This does not trim leading and trailing whitespace before underscore-replacement (use strip)
  • This does not remove embedded whitespace before replacement
  • There are other edge cases covered by matlab.lang.makeValidName
  • There are additional validity checks in matlab.lang.makeValidName
  2 commentaires
Stephen23
Stephen23 le 20 Mai 2024
Note that '[^a-zA-Z_0-9]' can be replaced with '\W'.
Jannik
Jannik le 21 Mai 2024
Such a "MetaCharacter" like '\W' was what I was looking for. Thanks to both of you! I appreciate your quick responses.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by