How to check if string contains some special character?

42 次查看(过去 30 天)
Dear all,
I have a question that the best way to check if string contains:
  1. alphanumeric characters and underscore only (ex: stringabc: return 1, string abc: return 0)
  2. underscore at the beginning or the end (ex: _stringabc, stringabc_ : return 0)
  3. consecutive underscores (ex: string__abc : return 0)
  4. numbers at the beginning (ex: 012string_abc : return 0)
Thank you so much

采纳的回答

Image Analyst
Image Analyst 2020-12-15
For #1 you could use isstrprop().
For #2, see startsWith(str, '_') and endsWith(str, '_')
For #3, you can use find():
indexes = strfind(str, '__');
For #4 you could do something like
if str(1) >= '0' && str(1) <= '9'
% str starts with a numerical digit.
else
% str does not start with a numerical digit.
end
  2 个评论
galaxy
galaxy 2020-12-15
编辑:galaxy 2020-12-15
Thank you so much
For #1 you could use isstrprop().
But alphanum option of isstrprop() function access other language character.
I want to check if string contains (a-zA-Z,0-9) and underscore(_) only.
>> str = 'あかき';
>> TF = isstrprop(str, 'alphanum')
TF =
1×3 logical array
1 1 1
Image Analyst
Image Analyst 2020-12-15
Sorry, I don't know that language. But you can always (I think) use logical comparison like
itsAChar = str(1) >= 'a && str(1) <= 'z'
where you just put in the lowest unicode character and highest unicode character instead of a and z.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by