Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
Jannik
Jannik el 17 de Mayo de 2024
Comentada: Jannik el 21 de Mayo de 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.

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by