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

조회 수: 4 (최근 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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by