Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Adam Danz
Adam Danz il 17 Mag 2024
Modificato: Adam Danz il 20 Mag 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 Commenti
Stephen23
Stephen23 il 20 Mag 2024
Note that '[^a-zA-Z_0-9]' can be replaced with '\W'.
Jannik
Jannik il 21 Mag 2024
Such a "MetaCharacter" like '\W' was what I was looking for. Thanks to both of you! I appreciate your quick responses.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by