フィルターのクリア

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

1 回表示 (過去 30 日間)
Jannik
Jannik 2024 年 5 月 17 日
コメント済み: Jannik 2024 年 5 月 21 日
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.

採用された回答

Adam Danz
Adam Danz 2024 年 5 月 17 日
編集済み: Adam Danz 2024 年 5 月 20 日
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 件のコメント
Stephen23
Stephen23 2024 年 5 月 20 日
Note that '[^a-zA-Z_0-9]' can be replaced with '\W'.
Jannik
Jannik 2024 年 5 月 21 日
Such a "MetaCharacter" like '\W' was what I was looking for. Thanks to both of you! I appreciate your quick responses.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by